java - 在 for 循环中更改 `double` 输出

标签 java for-loop counter

首先我想说我是这方面的新手。我正在尝试制作一个 for 循环,它将向我展示转换为 MPH 的不同 40 码短跑时间。问题是正在显示的输出:

5.96 40 Time is 13.727882855399633 Miles Per Hour 
6.96 40 Time is 11.755485893416928 Miles Per Hour 
7.96 40 Time is 10.27866605756053 Miles Per Hour 

我希望它显示为 5.96、5.97、5.98 等,而不是 5.96 和 6.96。

有没有人了解我正在尝试做的事情以及如何解决我遇到的这个问题?

public class FortyToMPH {

    public static void main (String args []) {
        double yards, foot, FeetInMiles, SecondsPerHour,FeetLength; 
        double FortyTime, Minutes, SecondsPerMile, MPH; 
        int counter;


        counter = 0;

        for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {  
        yards = 40; // length in yards
        foot = yards * 3; // convert to feet
        System.out.println();

        FeetInMiles = 5280; // The number of feet in a Mile
        SecondsPerHour = 3600;

        FeetLength = FeetInMiles / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
        System.out.println();

        SecondsPerMile = FeetLength * FortyTime;
        MPH = SecondsPerHour / SecondsPerMile;
        System.out.println(FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");

        counter++;
        // every 10th line, print a blank line
        if(counter == 10) {
            System.out.println();
            counter = 0; // reset the line counter


        }

        }
    }
}

最佳答案

问题是您在 for 循环定义中使用了 ++ 运算符:

for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) { 

将 for 循环更改为 while 循环,其中包含一行每次循环将 FortyTime 递增 0.01:

while(FortyTime <= 7.99) { 
    FortyTime += 0.01;
    // execute the rest of your code here
}

MarounMaroun 正确地指出,使用 double 作为循环计数器存在严重的浮点运算错误的风险,因此我将 for 循环更改为 while 循环。

++ 运算符的意思是“将 x 的值重新分配为 x + 1”。它只会给你 1 的增量(或减量,--)。

请注意,这将在完成之前打印出数百行。

关于java - 在 for 循环中更改 `double` 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647041/

相关文章:

java - 我正在使用框架布局,在其中我想要一个 ListView 和一个 float 操作按钮,但 ListView 不会扩展

使用 For 循环的 Javascript 计算

r - 在 Rstudio 的 RMarkdown 中循环生成 Pander 表

php - 将 div.container 包裹在 foreach 中

java - JSP 中的页眉、页脚、左侧和右侧模板

java - 断言或mockito验证可重用性-错误行

java vector 作用域

jquery - 如何在jquery数据:中添加(for循环)

java - 您如何从数组列表中提取项目并对它们进行计数,以便在 Java 中根据元素及其总计数(正确地)创建映射?

android - TextView.setText() 正在按下按钮,但不适用于 CountDownTimer