我输入了正确的值但打印了错误的值

问题描述 投票:1回答:2

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

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”而不是“正确!”我该怎么办?

java
2个回答
4
投票

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

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

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

0
投票

尽管两个浮点变量(比如a和b)在数学上具有相同的值,但它们的相等性可能不会返回true,即a == b可能不是真的。因此,我们发现差异是否可以忽略不计。所以,请尝试以下方法:

import java.util.*;

class Solution{
    public static void main(String args[]){
        Scanner s = new Scanner(System.in);
        int n1 = 6, n2 = 7;

        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

        double num = answer1 * n2 + answer2; //calculate user's number
        if (Math.abs(new Double(n1) - num) <= 0.1f)
            System.out.print("Correct!");
        else{
            System.out.print("Incorrect: ");  //error point I think
            double quotient = new Double(n1) / new Double(n2);
            double remainder = new Double(n1) - quotient * new Double(n2);
            System.out.printf("%d / %d = %f, Remainder: %f \n", n1, n2, quotient, remainder);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.