Justin Langley - 7 months ago 64

C++ Question

I'm supposed to be making a simple console program which can allow a user to input their miles driven and gallons used during multiple trips. It uses a while loop structure and calculates two fuel economies, one for the trip, and the overall fuel economy. My problem is getting my output to match what is in the book I'm learning from. Its close, but not spot on.

This is the output from the book:

`Enter miles driven (-1 to quit): 287`

Enter gallons used: 13

MPG this trip: 22.076923

Total MPG: 22.076923

Enter miles driven (-1 to quit): 200

Enter gallons used: 10

MPG this trip: 20

Total MPG: 21.173913

Enter miles driven (-1 to quit): 120

Enter gallons used: 5

MPG this trip: 24

Total MPG: 21.678571

This is what I've done so far:

`#include <iostream>`

int main ( )

{

// Set our variables and initialize them

double miles = 0;

double gallons = 0;

double economyTrip = 0;

double economyTotal = 0;

while (miles >= 0)

{

std::cout << "Enter miles driven (-1 to quit): ";

std::cin >> miles ;

// Check input

if (miles == -1)

break;

else

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

std::cin >> gallons;

// Calculate trip fuel economy

economyTrip = (miles/gallons) ;

// Calculate total fuel economy

if (economyTotal == 0)

economyTotal = economyTrip;

else

economyTotal += (economyTrip - economyTotal)/2;

// Display the results

std::cout << "MPG this trip: " << economyTrip << std::endl;

std::cout << "Total MPG:" << economyTotal << std::endl << "\n";

}

}

Am I wrong in the way I am averaging? I know that on a calculator, if you take the average of the three trip mileages you get around 22.02563 . . .

So, to say the least the book is slightly closer than I am. I am wondering how I can do this differently so I can get a closer answer. Or is this something I should even worry about?

Answer

You can't keep calculating MPG and adding it to a running total. You need to store *total miles* and *total gallons* and then calculate MPG at the end.

Source (Stackoverflow)