-2

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?

  • 3
    you are wrong. avg(avg(a,b),c)=((a+b)/2 + c)/2 is not the same as avg(a,b,c)=(a+b+c)/3. work out the math for yourself. – thang Mar 08 '14 at 18:04
  • Here is a cold fusion worked example: http://www.bennadel.com/blog/1627-Create-A-Running-Average-Without-Storing-Individual-Values.htm Basically, currentAverage * ElementsCount / ElementsCount+1 – MatthewMartin Mar 08 '14 at 18:07
  • That cold fusion is inefficient. Just keep a tally and count. Divide when you need to get the average. – thang Mar 08 '14 at 18:08

5 Answers5

2

Your formula for computing total economy is wrong. You should take sum of miles driven and divide it by sum of fuel used.

Bargor
  • 622
  • 1
  • 6
  • 13
  • Ok, yeah. I feel like a real tard for not noticing that. Over time that would probably be quite off the way I was doing it. – Justin Langley Mar 08 '14 at 18:20
1

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.

LeonardBlunderbuss
  • 1,264
  • 1
  • 11
  • 22
1

There are two ways to obtain the average:

  1. The simplest: keep a count for both quantities, divide at the end
  2. More complicated: average at each iteration (which takes some maths)

There is normally little benefit in using the second and more complicated method, so I suggest you keep up with the first.


Just for fun, let's do it the second way... but let's first understand what we are doing.

avg1 = a

avg2 = (a + b) / 2

avg3 = (a + b + c) / 3 = (a + b) / 3 + c / 3

                       = (a + b) * 2 / (2 * 3) + c / 3

                       = (a + b) / 2 * (2 / 3) + c / 3

                       = avg2 * (2 / 3) + c / 3

avg4 = (a + b + c + d) / 4 = avg3 * (3 / 4) + d / 4

and thus: avg[N] = avg[N-1] * (N - 1) / N + val[N] / N which starts to feel like a barycenter :) Note: avg[N-1] * (N-1) is actually the total up to N-1!

Thus, instead of keeping the total of miles and gallons, we can keep the average of miles/gallons and the total of gallons (in Python, just to show the principle):

avgMiles = 0.0
totGallons = 0.0

while True:
    miles = float(raw_input("Enter miles driven: "))
    gallons = float(raw_input("Enter gallons used: "))

    print "MPG this trip:", miles / gallons

    newTotGallons = totGallons + gallons
    avgMiles = avgMiles * totGallons / newTotGallons + miles / newTotGallons
    totGallons = newTotGallons

    print "Total MPG:", avgMiles

And the output is (or would be if it were interactive):

Enter miles driven: 200
Enter gallons used: 10
MPG this trip: 20.0
Total MPG: 20.0
Enter miles driven: 100
Enter gallons used: 10
MPG this trip: 10.0
Total MPG: 15.0
Enter miles driven: 50
Enter gallons used: 5
MPG this trip: 10.0
Total MPG: 14.0
Enter miles driven: 

By the way, instead of -1, it's customary to use CTRL+D to signal the end of user input (on Linux, at least).

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

Just came across this a while later than it was posted. I have the same homework assignment, except for C (not C++) so there are some minimal differences. I've solved it and I'll put the solution here for anyone who may come across this post in the future.

#include <stdio.h>

int main()
{
 float gallons, miles, mpg, averagempg, gallonstotal, milestotal;

 gallons = 0;
 miles = 0;
 mpg = 0;
 averagempg = 0;
 gallonstotal = 0;
 milestotal = 0;

 printf("\nEnter gallons used (-1 to end): ");
 scanf("%f", &gallons);

 while (gallons != -1) {

     gallonstotal = gallonstotal + gallons;

     printf("Enter the miles driven: ");
     scanf("%f", &miles);

     milestotal = milestotal + miles;
     mpg = miles / gallons;

     printf("The miles / gallon for this tank was %f \n", mpg);

     printf("\nEnter gallons used (-1 to end): ");
     scanf("%f", &gallons);
 }

 if (gallonstotal != 0){
     averagempg = milestotal / gallonstotal;
     printf("\nThe overall average miles/gallon was %f \n", averagempg);
 }
 else {
     puts("Error: no gallons were entered \n");
 }
}
griffinc
  • 649
  • 1
  • 10
  • 17
0
#include <iostream>
using namespace std;

int main()
{

unsigned int tripCounter = 0;
double tripMPG = 0;
double totalTripMPG = 0;

cout << "Enter miles driven (-1 to quit): ";
double miles = 0;
cin >> miles;

while ( miles != -1 )
{       
    cout << "Enter gallons used: ";
    double gallons = 0;
    cin >> gallons;

    tripMPG = miles / gallons;

    cout << "MPG this trip: " << tripMPG << endl;

    tripCounter = tripCounter + 1;
    totalTripMPG = totalTripMPG + tripMPG;

    double avgMPG = static_cast< double >( totalTripMPG ) / tripCounter;

    cout << "Total MPG: " << avgMPG << endl;
    cout << endl;

    cout << "Enter miles driven (-1 to quit): ";
    cin >> miles;
}

 system("pause");
}