# Thread: i need help with my c programm...Plzzzz

1. ## i need help with my c programm...Plzzzz

Hi folks i have a lil problem coz of my c progie.......

Hears the question its from C How to programmm 3/e from Deitel & Deitel

3.17 ) Develop a program that will input the miles driven and gallons used for each tankful.The program should calculate and display the miles per gallon obtained for each tankful.After processing all input information, the program should calculate and print the combined miles per gallon obtained for all tankfuls.

Below is the output screen :_ ---
|

Enter the gallons used ( -1 to end ): 12.8
Enter the miles driven: 287
The miles/ gallon for this tank was 22.421875

Enter the gallons used ( -1 to end ): 10.3
Enter the miles driven: 200
The miles/ gallon for this tank was 19.417475

Enter the gallons used ( -1 to end ): 5
Enter the miles driven: 120 The miles/ gallon for this tank was 24.000000

Enter the gallons used ( -1 to end ): -1

The overall average miles/gallon was 21.601423
|

And below is the program that i made and my luck it dint work the way it should:-

#include <stdio.h>

int main()
{
int miles, cnt =0;
float avg, mg= 0, gall;

while ( gall != -1 ) {
printf ("\nEnter the gallons used (-1 to end): ");
scanf ("%f", &gall);
if ( gall == -1 )
break;
printf ("\nEnter the miles driven: ");
scanf ("%d", &miles );
mg =( float )miles/gall;
printf ("The miles / gallon for this tank was %f\n", mg );
cnt = cnt + 1;
}

if ( gall == -1 ){
avg = (float)mg/cnt;
printf ("The overall average miles / gallon was %f", avg ); }

return 0;
}

Thanks for reading my boring ?question?

2. First off, if you're going to post code, please use code tags in future.

>...it dint work the way it should
OK, so it didn't do what you wanted. So tell us what it is or isn't doing to your requirements, my crystal ball is a bit blury this time of night!

So, anyway, I run it and I'm going to guess you're complaining that it isn't totaling correctly. This is probably to do with the fact you are not storing the mg value, you just overwrite it each loop. Look here:

>avg = (float) mg / cnt;
cnt tells us how many times we did the loop, but mg holds the data from only the last iteration.

I'll leave the coding for you to work out......