欢迎来到天天文库
浏览记录
ID:38698769
大小:48.50 KB
页数:6页
时间:2019-06-17
《实验练习--类的定义与调用》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验1有理数的类封装模板代码Rational.javapublicclassRational{intnumerator,denominator;Rational(){}Rational(inta,intb){setNumeratorAndDenominator(a,b);}voidsetNumeratorAndDenominator(inta,intb){//设置分子和分母intc=f(Math.abs(a),Math.abs(b));//计算最大公约数numerator=a/c;denominator=b/c;if(numerator<
2、0&&denominator<0){numerator=-numerator;denominator=-denominator;}}intgetNumerator(){returnnumerator;}intgetDenominator(){returndenominator;}intf(inta,intb){//求a和b的最大公约数if(a
3、merator();intb=r.getDenominator();intnewNumerator=numerator*b+denominator*a;intnewDenominator=denominator*b;Rationalresult=newRational(newNumerator,newDenominator);returnresult;}Rationalsub(Rationalr){inta=r.getNumerator();intb=r.getDenominator();intnewNumerator=numerator
4、*b-denominator*a;intnewDenominator=denominator*b;Rationalresult=newRational(newNumerator,newDenominator);returnresult;}Rationalmuti(Rationalr){inta=r.getNumerator();intb=r.getDenominator();intnewNumerator=numerator*a;intnewDenominator=denominator*b;Rationalresult=newRatio
5、nal(newNumerator,newDenominator);returnresult;}Rationaldiv(Rationalr){inta=r.getNumerator();intb=r.getDenominator();intnewNumerator=numerator*b;intnewDenominator=denominator*a;Rationalresult=newRational(newNumerator,newDenominator);returnresult;}}Computer.javapublicclassC
6、omputer{publicstaticvoidmain(Stringargs[]){Rationalr1;【代码1】//创建分子、分母分别为1和5的有理数r1Rationalr2;【代码2】//创建分子、分母分别为3和2的有理数r2Rationalresult=【代码3】//r1调用方法和r2做加法运算inta=【代码4】//result调用方法返回自己的分子intb=【代码5】//result调用方法返回自己的分母doublep=a;doubleq=b;doubledoubleResult=p/q;System.out.print("
7、分数"+r1.getNumerator()+"/"+r1.getDenominator());System.out.print("与分数"+r2.getNumerator()+"/"+r2.getDenominator()+"的和等于");System.out.println(a+"/"+b+"="+doubleResult);r1.setNumeratorAndDenominator(4,7);r2.setNumeratorAndDenominator(-5,20);result=r1.muti(r2);a=result.getNume
8、rator();b=result.getDenominator();p=a;q=b;doubleResult=p/q;System.out.print("分数"+r1.getNumerator
此文档下载收益归作者所有