-3
int main(void)
{
StartUp(); //indicates beginning of code
double startmileage{ 0 }; //indicates starting mileage, initialized at the value of 0
double endmileage{ 0 }; //indicates ending mileage, initialized at the value of 0
double milesdriven{ 0 }; //indicates total miles driven, initialized at the value of 0
double gallonsused{ 0 }; //indicates total gallons used, initialized at the value of 0
double milespergallon{ 0 }; //indicates total miles per gallon, initialized at the value of 0
double totalgallonsused{ 0 };
double totalmilesdriven{ 0 };
while (true)
{
cout << "Enter the gallons used (-1 to end): "; //prompts user to enter total number of gallons used for trip
cin >> gallonsused; //user enters data
totalgallonsused += gallonsused;
if (gallonsused == -1)
{
break; // Check for sentinel value of -1
}
cout << "Enter starting mileage: "; //prompts user to enter start mileage for trip
cin >> startmileage; //user enters data
cout << "Enter ending mileage: "; //prompts user to enter end mileage for trip
cin >> endmileage; //user enters data
milesdriven = endmileage - startmileage; //calculates total miles driven
totalmilesdriven += milesdriven;
cout << "Miles driven: " << milesdriven << endl; //outputs total miles driven to screen
milespergallon = milesdriven/gallonsused; //calculates total miles per gallon
cout << "The miles/gallon for this tank was: " << milespergallon << endl; //outputs miles per gallon to screen
cout << "\n\n" << endl;
}
// Show grand totals
cout << "\n\nGrand totals: " << endl;
cout << "Total gallons used: " << totalgallonsused << endl;
cout << "Total miles driven: " << totalmilesdriven << endl;
cout << "The overall average verage miles/gallon: " << milespergallon <<endl;
cout << "\n\n" << endl;
WrapUp();
這裏是輸出:C++菜鳥有問題越來越總計報名
Enter the gallons used (-1 to end): 12.8
Enter starting mileage: 0
Enter ending mileage: 287
Miles driven: 287
The miles/gallon for this tank was: 22.4219
Enter the gallons used (-1 to end): 10.3
Enter starting mileage: 287
Enter ending mileage: 487
Miles driven: 200
The miles/gallon for this tank was: 19.4175
Enter the gallons used (-1 to end): 5
Enter starting mileage: 487
Enter ending mileage: 607
Miles driven: 120
The miles/gallon for this tank was: 24
Enter the gallons used (-1 to end): -1
Grand totals:
Total gallons used: 27.1
Total miles driven: 607
The overall average verage miles/gallon: 24
Program Program2.cpp ended successfully.
Press any key to continue . . .
謝謝,帕迪!這些要求是在每次輸入後要求平均值,這就是爲什麼我在總和之前把它放在那裏的原因。所以我做出了你所推薦的改變,現在它已經給出了總計,儘管我認爲平均MPG仍然在最後一次進入。這裏是我的修改: – Clarky7782
不得不修改我最初的問題來獲取代碼。請參閱上面的修改 – Clarky7782
對不起,有問題編輯。現在更新的代碼已經存在。 – Clarky7782