我输入了正确的值,但是打印了错误的值。 (*商号显示到小数点后第一位。)

System.out.printf ("What is quotient of %d / %d ? ", n1, n2);
double answer1 = s.nextDouble();  //enter quotient

System.out.printf("What is remainder of %d / %d ? ", n1, n2);
double answer2 = s.nextDouble();  //enter remainder

if ((quotient == answer1) && (((n1-(quotient*n2)) == answer2)))
  System.out.print("Correct!");

else {  System.out.print("Incorrect: ");  //error point I think
System.out.printf("%d / %d = %f, Remainder: %f \n", n1, n2, quotient, (n1-(quotient*n2)));   }


当问题是6/7时,如果我输入正确答案0.8,而其余的0.4,则显示“错误:6/7 = 0.800000,余数:0.400000”,而不是“正确!”。我该怎么办?

最佳答案

这是由于浮点运算和精度。差异可能在逗号后的第十位。因此,不应将浮点数与==进行比较,而应检查它们的差值是否低于某个阈值。

double a = ...;
double b = ...;

if (Math.abs(a-b) < 0.0001) {
  //Consider as equal
} else {
  //Consider as unequal
}

10-07 19:36