I have a homework assignment due this week and am fairly new to C++. Don't have a book so I can't really go on anything other than the video material and power point slides my teacher provides. I have 98% of the assignment done, however I'm encountering logic problems. I'm not a new programmer so I do have programming knowledge, mainly just C# though. I'm 99% sure that I'm over analyzing my problem, but this is the way I want to do it so just bare with me here. My problem is with determining the average miles per gallon. The assignment requires me to use a while loop to continuously receive information from the user until they wish to quit. The problem with determining the average is that it's not presenting the correct average after the 1st entry. Any help is appreciated.

Please note I'm not wanting a code snippet that will work better or work period, I just wish to know what I'm doing wrong so I can correct it.

#include<iostream>

using namespace std;

float MPG(float MilesTraveled, float GasUsed) { return MilesTraveled / GasUsed; }
float AVG(float NewMPG, float OldMPG, int loop)
{
	if (loop == 1)
		return NewMPG;

	else
		return NewMPG + OldMPG / loop; 
}

int main()
{
	float MilesTraveled = 1;
	float GasUsed = 1;
	float CurrentMPG = 0;
	float AvgMPG = 0;
	int loop = 1;

	while (MilesTraveled > 0)
	{
		cout << "Enter the miles you traveled (enter -1 to exit): ";
		cin >> MilesTraveled;

		if (MilesTraveled == -1)
			break;

		cout << "Enter how many gallons of gas you used: ";
		cin >> GasUsed;

		CurrentMPG = MPG(MilesTraveled, GasUsed);

		AvgMPG = AVG(CurrentMPG, AvgMPG, loop);

		cout << CurrentMPG << " Miles Per Gallon this tank.\n" << AvgMPG << " Miles Per Gallon on average.\n";
		
		loop++;
	}
}

Thank you in advance,
Jamie

Edited 4 Years Ago by lxXTaCoXxl: n/a

I'm not sure of your proboem. Please provide sample input with expected output and observed output.

My best guess as to your problem is you can't add current average miles per gallop to previous average and divide that by number of "loops" to get overall average. Keep track of total miles and total gallons in addition to current miles and current gallons.

Edited 4 Years Ago by Lerner: n/a

This question has already been answered. Start a new discussion instead.