有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的增量计算不正确?

我运行了一个for循环,它要求他们输入增量数。但当它输出表格时,它实际上是增量的两倍。所以如果我把10放在incr里,它会上升20。请帮忙

for (double x = fah1; x <= fah2; x+=incr) {
    double cel = 5/9.0 * (x-32);
    if (x <= 99){
        System.out.println(x + "               " + df.format(cel);
        x+= incr;
    }
    else {
        System.out.println(x + "              " + df.format(cel));
        x+=incr;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    递增两次,一次在for循环声明中,一次在if-then-else语句中:

    尝试将其更改为:

    for (double x = fah1; x <= fah2; x+=incr) {
        double cel = 5/9.0 * (x-32);
        if (x <= 99){
            System.out.println(x + "               " + df.format(cel);
            // Remove the increment from here
        }
        else
        {
            System.out.println(x + "              " + df.format(cel));
            // Remove the increment from here
        }
    }