I am working independently through Deitel's How to Program C and I am having some difficulty with sentinel values. The problem is that the sentinel value doesn't stop the program, but instead uses the sentinel value( in this case -1) in the calculation. This leads to averages that are negative or far from the correct value. Please help. Here is what I have so far, if it helps.
also - I am using visual c++ 2005 express addition, and i am constantly having to insert the first piece of code (#define _CRT_SECURE_NO_DEPRECATE)
because visual c++ wants me to use scanf_s instead of scanf. Is this normal?
Code:
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
int main( void )
{
int miles, gallons, totalmiles, totalgallons;
float mpg, totalmpg;
totalmiles = 0, totalgallons = 0;
printf( "Enter the gallons used (-1 to end): " );
scanf( "%d", &gallons );
totalgallons = totalgallons + gallons;
printf( "Enter the miles driven: " );
scanf( "%d", &miles );
totalmiles = totalmiles + miles;
mpg = ( float )miles / gallons;
printf( "The miles/gallon for this tank was %.6f\n", mpg );
while ( gallons != -1 ) {
printf( "Enter the gallons used (-1 to end): " );
scanf( "%d", &gallons );
totalgallons = totalgallons + gallons;
printf( "Enter the miles driven: " );
scanf( "%d", &miles );
totalmiles = totalmiles + miles;
mpg = miles / gallons;
printf( "The miles / gallon for this tank was %.6f\n", mpg );
}
if ( totalmiles != 0 ) {
totalmpg = ( float )totalmiles / totalgallons;
printf( "The overall average miles/gallon was %.6f\n", totalmpg );
}
else {
printf( "No gallons were entered\n" );
}
return 0;
}