-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

最初のパスの NaN の結果はtotalgallons0 のままである可​​能性があります。ゼロで割ることができないため、結果は非数 (NaN) になります。

算術の順序により、各反復で表示される値は、その反復で入力された値を使用していません。たとえば、から取得したばかりtotalmilesの を含める必要があります。milesinput

ロジックは次のようになります。

// 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 に答える