标签:osc 分享 not and 掌握 logs 准备 语句 编程
implements Comparable<RationalNumber2>
声明要实现Comparable接口。public class RationalNumber2 implements Comparable<RationalNumber2>
public int compareTo(RationalNumber2 op2)
将RationalNumber2中的对象数值转化为浮点值,再与定义好的误差标准比较(理由:参考week5学习总结中的浮点数值比较时的较好方法)。
double n1, n2, difference;
n1 = (double) numerator / denominator;
n2 = (double) op2.getNumerator() / op2.getDenominator();
difference = Math.abs(n2 - n1);
if(difference < 0.0001)
return -1;
else
if (difference > 0.0001)
return 1;
else
return 0;
测试程序代码
public class RationalTester2
{
//----------------------------------------------------------------------
// Creates some rational number objects and performs various
// operations on them.
//----------------------------------------------------------------------
public static void main(String[] args)
{
RationalNumber2 r1 = new RationalNumber2(1, 3);
RationalNumber2 r2 = new RationalNumber2(1, 9);
RationalNumber2 r3, r4, r5, r6, r7;
System.out.println("First rational number: " + r1);
System.out.println("Second rational number: " + r2);
if (r1.isLike(r2))
System.out.println("r1 and r2 are equal.");
else
System.out.println("r1 and r2 are NOT equal.");
if (r1.compareTo(r2) == 1 )
System.out.println(" r1 > r2 ");
else
if (r1.compareTo(r2) ==-1)
System.out.println(" r1 < r2 ");
else
System.out.println("r1 = r2");
r3 = r1.reciprocal();
System.out.println("The reciprocal of r1 is: " + r3);
r4 = r1.add(r2);
r5 = r1.subtract(r2);
r6 = r1.multiply(r2);
r7 = r1.divide(r2);
System.out.println("r1 + r2: " + r4);
System.out.println("r1 - r2: " + r5);
System.out.println("r1 * r2: " + r6);
System.out.println("r1 / r2: " + r7);
}
}
20172319 2018.04.11 《Java程序设计教程》第7周课堂测验(补写博客)
标签:osc 分享 not and 掌握 logs 准备 语句 编程
原文地址:https://www.cnblogs.com/Tangcaiming/p/8799258.html