开发者

Unable to make program calculate correctly

I am trying to make a program which does a very basic calculation, but for some reason i can't get the code right. It is supposed to calculate the miles per gallon for one trip. You can 开发者_开发技巧then add this info multiple times (for different trips) and for each time it should calculate the total miles per gallon (i.e. the average miles per gallon of all the trips). This is the code:

#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
int counter = 1;
double milePerRe, milePerTo = 0, x, y;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
cout << "Enter gallons: ";
cin >> y;
while (x != -1)
{
      milePerRe = x/y;
      milePerTo += milePerRe;
      milePerTo /= counter;
      cout << "MPG this tankful: " << setprecision( 6 ) << fixed << milePerRe;
      cout << "\nTotal MPG: " << setprecision( 6 ) << fixed << milePerTo << endl << endl;
      counter++;
      cout << "Enter the miles used (-1 to quit): ";
      cin >> x;
      if (x != -1)
      {
      cout << "Enter gallons: ";
      cin >> y;
      }
}
system("pause");
return 0;
}

When I run the program and say I enter 10 on the miles and 1 on the number of gallons the first time and the second time, everything works fine. Then if i do it again a third time the calculations begin to become incorrect.


You can not calculate average of averages the way you do it. In your code you are dividing by the counter EACH iteration, while you should divide it only at the end. Best way to do what you need is something like this:

...
double totalMiles = 0;
double totalGallons = 0;
...
while (x != -1)
{
     milePerRe = x/y;
     totalMiles += x;
     totalGallons += y;
     milesPerTo = totalMiles / totalGallons;
...

However, if your task was to explicitly calculate the average of trips (not the average of miles/gallons), you would need to introduce another variable, like this:

...
double currentMilesPerTo;
...
while (x != -1)
{
    milePerRe = x/y;
    milePerTo += milePerRe;
    currentMilesPerTo = milePerTo/counter;
    ....
    cout << "\nTotal MPG: " << currentMilesPerTo;
    ...


the value of x and y are not being updated properly i guess.after every iteration try to make x and y to zero. hope it works this way

TNQ

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜