I have a homework assignment to write a program about mileage. I've been able to get it to work, well except the average doesn't calculate correctly and I haven't been able to verifiy the users input. I'm using Visual C as my compiler.
Can someone help me with checking the users input and how to get the average to calculate correctly?
#include <stdio.h>
int main ()
{
/* Declare variables */
char a = 0, z = 0, A = 0, Z = 0;
float gallons, miles;
float totalGallons = 0;
float totalMiles = 0;
float tank = 0;
float average = 0;
/* Greetings and instructions to user */
printf( "\nAt the first prompt please enter the gallons used or -1 to exit program.\n"
"At the second prompt enter the miles that was driven. I will calculate\n"
"the total miles per gallon. After you type -1 to end the program, I will\n"
"give you the average of your total miles per gallon.");
/* Ask for gallons or sentinel value from user */
printf( "\n\n\nEnter the gallons used (-1 to end): ");
scanf( "%f", &gallons ); /* read users input */
if (gallons == a - z || A - Z){
fprintf( stderr, "You entered a letter. Please enter a number.\n" );
}
/* Start loop and calculation */
while ( gallons != -1 ) {
/* Ask for miles from user */
printf( "\nEnter the miles driven: ");
scanf( "%f", &miles );
/* Calculate useage */
tank = miles / gallons;
printf( "\nThe miles / gallon for this tank was: %.6f.\n\n", tank);
/* Ask user for gallons or sentinel value */
printf( "\nEnter the gallons used (-1 to end): ");
scanf( "%f", &gallons );
/* Calculate useage */
totalGallons = totalGallons + gallons;
totalMiles = totalMiles + miles;
/* Exit loop */
}
/* Calculate and print average */
average = (float)totalMiles / totalGallons;
printf( "\n\nThe overall average miles/gallon was: %.6f.\n\n", average);
/* Exit program */
return 0;
}