-omitted code-
{
while(miles != -999)
{
System.out.print("Enter the numbers of gallons purchased: ");
gallons = input.nextDouble();
totalmpg = (totalmiles / totalgallons);
totalgallons = totalgallons + gallons;
System.out.printf("Your miles per gallon this tank was:%.2f\n ", mpgthistank);
mpgthistank = miles / gallons;
System.out.printf("Your total miles driven is:%.2f\n ", totalmiles);
totalmiles = totalmiles + miles;
System.out.printf("Your total gallons used is:%.2f\n: ", totalgallons);
totalgallons = totalgallons + gallons;
System.out.printf("Your total miles per gallon is:%.2f\n ", totalmpg);
totalmpg = totalmiles / totalgallons;
System.out.print("Enter the number of miles traveled<-999 to quit>: ");
miles = input.nextDouble();
}
不完全确定原因。这是我得到的运行:
Enter miles driven since last full tank <-999 to quit>: 100
Enter the numbers of gallons purchased: 10
Your miles per gallon this tank was:0.00
Your total miles driven is:0.00
Your total gallons used is:10.00
Your total miles per gallon is:NaN
Enter the number of miles traveled<-999 to quit>:
But it should read:
Your miles per gallon this tank was: 10
Your total gallons used is: 10
Your total miles per gallon is: 10
...然后循环应重新开始(它确实如此)。我确信这是一个简单的语法错误,但我不能指出错误。
答案 0 :(得分:1)
您正在计算打印后的变量结果。当然它不起作用。只需在实际计算后移动打印语句。
其次,你正在进行两次计算,这是没有意义的。另外请记住,根据您的需要,您需要将某些变量更新为零。如果你想每次独立计算所有内容,totalgallons = totalgallons + gallons
将为每个循环传递聚合加仑...这可能是你真正想要的,但可能不是。
答案 1 :(得分:1)
看看这个:
System.out.printf("Your miles per gallon this tank was:%.2f\n ", mpgthistank);
mpgthistank = miles / gallons;
首先打印该值,然后计算它。
反转语句 - 首先计算值,然后打印它。
mpgthistank = miles / gallons;
System.out.printf("Your miles per gallon this tank was:%.2f\n ", mpgthistank);
答案 2 :(得分:1)
第一遍的NaN结果可能是因为totalgallons
仍为0.因为我们不能除以零,结果是非数字(NaN)。
由于算术的顺序,每次迭代时显示的值都不使用在该迭代上输入的值。例如,totalmiles
应该包含miles
刚刚获得的input
。
你的逻辑应该是这样的:
// Get input ...
// Do arithmetic
totalmiles += miles;
totalgallons += gallons;
mpgthistank = miles / gallons;
totalmpg = totalmiles / totalgallons;
// Print output ...
除了正确之外,这是编写示例代码的更简洁方法。如果您不熟悉+=
,则totalmiles += miles
是totalmiles = totalmiles + miles