# DEV-C++高手幫幫我

Drivers are concerned with the mileage obtained by their automobiles. One driver has kept

track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop

a program that will input the miles driven and gallons used for each tankful. The program

should calculate and display the miles per gallon obtained for each tankful. After processing all input

information, the program should calculate and print the combined miles per gallon obtained for all

tankfuls. Here is a sample input/output dialog:

******************************

Enter the gallons used: 12.8

Enter the miles driven: 287

The miles / gallon for this tank was 22.421875

Enter the gallons used: 10.3

Enter the miles driven: 200

The miles / gallon for this ta

### 3 個解答

• 最佳解答

#include <iostream>

int main()

{

double gallons_total = 0, miles_total = 0;

while (std::cin.good())

{

double gallons, miles;

std::cout << "Enter the gallons used: ";

if ((std::cin >> gallons).fail())

break;

std::cout << "Enter the miles driven: ";

if ((std::cin >> miles).fail())

break;

std::cout << "The miles / gallon for this tank was " << (miles / gallons) << std::endl;

gallons_total += gallons;

miles_total += miles;

}

std::cout << "The miles / gallon for all tanks were " << (miles_total / gallons_total) << std::endl;

}

輸入非合法浮點數可跳出.

2011-03-23 22:24:46 補充：

回答 001 有精度問題.

輸入 10 200 11 200, 總共用了 21 gallon, 跑了 400 miles, 應該是 19.0476 miles per gallon.

可是回答 001 會說 19.090909.

2011-03-24 03:19:17 補充：

舉例來說,

第一段路是高速公路, 5 gal 就跑了 200 miles. 40 miles / gal.

第二段路是越野路段, 20 gal 才跑 100 miles, 5 miels / gal.

照奇樂的算法, "平均" 是 (40 + 5) / 2 = 22.5 miles / gal, 可是 overall 實際上是 300 / 25 = 12 miles / gal.

後來想想, 題目中說 combined miles per gallon 到底是指哪個算法, 說真的我也搞不清楚 = =

• 匿名使用者
6 年前

到下面的網址看看吧

• #include <stdio.h>

#include <stdlib.h>int main(int argc, char *argv[])

{

double gallon,mile,total=0,i=0;

do{

printf("Enter the gallons used(-1 ESC):");

scanf("%lf",&gallon);

if(gallon<=-1){break;}

printf("Enter the miles driven:");

scanf("%lf",&mile);

printf("The miles / gallon for this tank was %lf",(double)mile/gallon);

i++; total+=(mile/gallon);

printf("\n");

}while(1);

if(i!=0)

printf("averge==%lf",total/i);

system("PAUSE");

return 0;

}