gpt4 book ai didi

java - 与选择混淆( float )

转载 作者:行者123 更新时间:2023-12-04 09:31:29 24 4
gpt4 key购买 nike

关闭。这个问题需要details or clarity .它目前不接受答案。












想改善这个问题吗?通过 editing this post 添加详细信息并澄清问题.

去年关闭。




Improve this question




我正在在线学习 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 语句。除法运算应输出浮点数,并应与变量 b 进行比较检查它是否在公差范围内。
如果将两个整数相除,则称为整数除法,它再次产生整数。要获得浮点数,您需要将至少一个数字转换为浮点数。这是区别以及如何进行类型转换:
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
与容差比较的另一点是,我们需要绝对差异进行比较。要做到这一点,有方法 abs()Math类(class): 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/

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