java - 与选择( float )混淆

标签 java math types

我正在在线学习 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/

相关文章:

java - 如何在java中计算字符串格式的大数模

c - 4 变量映射到数组

scala - Scala 中的 lambda 类型是什么?它们有什么好处?

C++ 数据类型及其范围

java - 我怎样才能模拟一个非空值?

Java 锁 : How equality check for Monitor locks is done in synchronized block?

javascript - 将动画重写为基于时间的(而不是基于平速的)

python - 通用单例的类型提示?

java - 教程第 6 部分中出现错误 : JSON Parsing and Android ListView Design

java - 这个查询来自哪里?