我正在在线学习 Java,但遇到了问题。我知道它可能与 BigDecimal 类有关,但除此之外我不确定。抱歉缩进不好。
public class Practice {
public static void main(String[] args) {
double b = 1.3333;
int c = 4, d = 3;
final double TOLERANCE = 0.001;
/*** TODO: Write an if statement to serve as the header for the conditional block below.
Execute the first block if the floating point outcome of c divided by d is
within the given TOLERANCE of b. ***/
{
System.out.println("Value within the tolerance level!");
} else {
System.out.println("Value outside the tolerance level!");
}
}
}
最佳答案
/*** TODO: Write an if statement to serve as the header for the conditional block below.
Execute the first block if the floating point outcome of c divided by d is
within the given TOLERANCE of b. ***/
您需要使用除法运算来完成缺失的 if 语句,该运算需要与公差进行比较。除法运算应输出 float ,并应与变量b
进行比较以检查其是否在容差范围内。
如果将两个整数相除,则称为整数除法,并且结果再次为整数。要获得 float ,您需要将至少一个数字转换为 float 。以下是差异以及转换的完成方式:
System.out.println(c / d); // result is 1, out of tolerance. this is integer division
System.out.println((float) c / d); // result is 1.3333334, within tolerance
关于公差的比较还有一点是我们需要绝对差来进行比较。为此,Math
类中有一个方法 abs()
:Math.abs(((float) c/d) - b)
所以你的代码最后应该是这样的:
public static void main(String[] args) {
double b = 1.3333;
int c = 4, d = 3;
final double TOLERANCE = 0.001;
if (Math.abs(((float) c / d) - b) < TOLERANCE){
System.out.println("Value within the tolerance level!");
} else {
System.out.println("Value outside the tolerance level!");
}
}
关于java - 与选择( float )混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62822742/