欢迎来到天天文库
浏览记录
ID:38801664
大小:28.00 KB
页数:6页
时间:2019-06-19
《支持查找功能的分数类》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、packageclasshandle;publicclassFractionClassSupportFindFunction{publicstaticvoidmain(Stringargs[]){Fractionfraction1=newFraction(0.25);System.out.println(fraction1);Fractionfraction2=newFraction(2,8);//分数相加Fractionfraction3=fraction1.add(fraction2);System
2、.out.println(fraction1+"+"+fraction2+"="+fraction3);Fraction[]fractions={newFraction(1,3),newFraction(1,5),newFraction(1,2),newFraction(1,4),newFraction(1,10)};//对数组排序,并使用二分折半查找法来搜索指定分数类变量java.util.Arrays.sort(fractions);//输出命中类变量的下标位置System.out.println(
3、"搜索的分数是第"+java.util.Arrays.binarySearch(fractions,fraction3)+"个");}}//支持查找功能的分数类classFractionimplementsComparable{publicintgetNumerator(){returnnumerator;}publicvoidsetNumerator(intn){numerator=n;reduct();}publicintgetDenominator(){returndenominator;}pub
4、licvoidsetDenominator(intd){if(d==0)denominator=1;elsedenominator=d;reduct();}//分子privateintnumerator;//分母privateintdenominator;//默认构造函数publicFraction(){}//对分子、分母初始化的构造函数publicFraction(intn,intd){setFraction(n,d);}//分数的设置函数,并且约分publicvoidsetFraction(intn
5、,intd){setNumerator(n);setDenominator(d);reduct();}//约分函数publicvoidreduct(){//求分子和分母的最小值intminValue=Math.min(Math.abs(numerator),Math.abs(denominator));//将小于分子和分母的最小值的整数,从大到小去除分子和分母,如果能够同时被整除,约分,并退出for(inti=minValue;i>=1;i--){if(numerator%i==0&&denominat
6、or%i==0){numerator=numerator/i;denominator=denominator/i;//System.out.println(numerator);//System.out.println(denominator);break;}}}//将双精度数转换为相应的分数publicFraction(doubled){convertToFraction(d);}//该函数将双精度数转化为相应的分数publicvoidconvertToFraction(doubled){intdec
7、imalCount=1;//求双精度数的字符长度intdLen=String.valueOf(d).length();//System.out.println(dLen);for(inti=0;i8、ction=newFraction();fraction.numerator=numerator*f.denominator+denominator*f.numerator;fraction.denominator=denominator*f.denominator;fraction.reduct();returnfraction;}//返回分数相减的结果,并且约分publicFractionminus(Fractionf){Fractio
8、ction=newFraction();fraction.numerator=numerator*f.denominator+denominator*f.numerator;fraction.denominator=denominator*f.denominator;fraction.reduct();returnfraction;}//返回分数相减的结果,并且约分publicFractionminus(Fractionf){Fractio
此文档下载收益归作者所有