-2
-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

...然后循环应该重新开始(它确实如此)。我确信这是一个简单的语法错误,但我无法指出错误。

4

3 回答 3

1

在打印变量之后,您正在计算变量的结果。当然是行不通的。只需在实际计算之后移动打印语句。

其次,你做了两次没有意义的计算。另请记住,您需要根据您的需要将一些变量更新为零。如果您想每次都独立计算所有内容,totalgallons = totalgallons + gallons则将为每个循环通过聚合加仑......这可能是您真正想要的,但可能不是。

于 2013-09-14T15:51:30.543 回答
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);
于 2013-09-14T15:51:45.307 回答
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

于 2013-09-14T16:11:30.987 回答