首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么将余数运算符与double一起使用会返回false?

为什么将余数运算符与double一起使用会返回false?
EN

Stack Overflow用户
提问于 2020-03-04 04:23:52
回答 2查看 55关注 0票数 0
代码语言:javascript
运行
复制
 public static void main(String[] args) {
    double s = 0; //Position
    double v = 100; //Velocity
    double g = 9.81; //Gravitational Force

    for(double time = 0.01; time < 100; time = time + 0.01){
       double DELTA_T = 0.01;
        s = s + (v * DELTA_T);
        v = v - (g * DELTA_T);

        if(time % 1 == 0) { //I want to print this out, but it seems to end the program with no output
            System.out.println("Seconds: " + time);
            System.out.println("Position: " + s);
            System.out.println("Velocity: " + v);
        }
    }
}

我想在(time %1 == 0)时输出计算结果。但是当我运行它的时候,它没有打印出任何东西。当我删除if语句并保留在print语句中时,它将打印出来。

我想知道我的if语句出了什么问题,我该如何尝试每次打印"s“、"v”和" time“(time %1 == 0)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-04 04:31:18

这里的问题很可能是因为您正在比较浮点值的相等性。有关我们在浮点数学和等式比较中遇到的问题,请参阅Is floating point math broken?

对于您的特定问题,我建议您使用表示百分之一秒的整数计数器。然后,您可以使用整数进行比较:

代码语言:javascript
运行
复制
 public static void main(String[] args) {
    double s = 0; //Position
    double v = 100; //Velocity
    double g = 9.81; //Gravitational Force

    for(int time = 1; time < 10000; time++) {
        double DELTA_T = 0.01;
        s = s + (v * DELTA_T);
        v = v - (g * DELTA_T);

        if(time % 100 == 0) { //I want to print this out, but it seems to end the program with no output
            System.out.println("Seconds: " + time);
            System.out.println("Position: " + s);
            System.out.println("Velocity: " + v);
        }
    }
}

这将解决您的打印问题。但是,您最希望看到的是sv没有正确的值。这是因为您在每次迭代中都会累积浮点数学中的错误。您应该在每次迭代时直接从time计算这些值,而不是现在这样做。

票数 -1
EN

Stack Overflow用户

发布于 2020-03-04 04:51:05

你的时变精度正在毁掉你的模数检查。你需要乘法并强制转换为int,才能得到一个好的结果:

代码语言:javascript
运行
复制
public static void main(String [] args {
    double s = 0; //Position
    double v = 100; //Velocity
    final double g = 9.81; //Gravitational Force
    final double DELTA_T = 0.01;

    for(double time = 0.01; time < 100; time += 0.01){
        s += (v * DELTA_T);
        v -= (g * DELTA_T);

        System.out.println(time);
        if (((int) (time * 100)) % 100 == 0) { 
            System.out.println("Seconds: " + time);
            System.out.println("Position: " + s);
            System.out.println("Velocity: " + v);
        }
    }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60514956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档