首先我想说我是这方面的新手。我正在尝试制作一个 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/