Hi, I have a problem that wants to be calculated only by while loop. (no other loop, no goto, break)
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. Here is a sample input/output dialog:
Enter the gallons used (0 to end): 12.8
Enter the miles driven: 287
The miles / gallon for this tank was 22.421875
Enter the gallons used (0 to end): 10.3
Enter the miles driven: 200
The miles / gallon for this tank was 19.417475
Enter the gallons used (0 to end): 5
Enter the miles driven: 120
The miles / gallon for this tank was 24.000000
Enter the gallons used (0 to end): 0
The overall average miles/gallon was 21.601423
Here is my attempt:
#include <stdio.h>
int main(void) {
int miles;
float gallons, mg, overall = 0, avg = 0;
while(gallons != 0) {
printf("Enter the gallons used (0 to end): ");
scanf("%f", &gallons);
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += mg;
avg++;
}
printf("The overall miles/gallon was: %f\n", overall/avg);
return 0;
}
Although the output is correct, but when i enter 0 to exit the loop, then overall miles shows something like this: -1.#IND00
And when I tried with by -1, then it calculates this with other inputs.
Something like that:
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): -1
Enter the miles driven: -1
The overall average miles/gallon was 11.710938
I use gcc compiler(4.7.2)