gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:23:10 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

关于java - 我输入了正确的值但打印了错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com