c - Unable to properly terminate "while" loop -
i'm trying out programming in c first time, , applying concrete stuff...
the program i'm creating problem deals while loop. goal of program calculate average miles per gallon set of trucks. want terminate -1 inputted number of gallons consumed, instead have input twice, once number of gallons, , once number of miles. have found input in fact used part of calculation of result. here code:
#include <stdio.h> int main() { int tanks, miles; float gallons = 0, average = 0, miles_per_gallon = 0; tanks = 0; while (gallons != -1) { tanks += 1; miles_per_gallon = (float)miles / gallons; average = average + miles_per_gallon; printf("the miles / gallon tank %.3f\n", miles_per_gallon); printf("enter gallons used (-1 end): "); scanf("%f", &gallons); printf("enter miles driven: "); scanf("%d", &miles); } average /= tanks; printf("the overall average miles/gallon %.3f", average); return 0; }
here sample output:
c:\>gallons enter gallons used (-1 end): 12.3 enter miles driven: 700 miles / gallon tank 56.911 enter gallons used (-1 end): 13.4 enter miles driven: 666 miles / gallon tank 49.701 enter gallons used (-1 end): 17.3 enter miles driven: 644 miles / gallon tank 37.225 enter gallons used (-1 end): 15.5 enter miles driven: 777 miles / gallon tank 50.129 enter gallons used (-1 end): -1 enter miles driven: -1 miles / gallon tank 1.000 overall average miles/gallon 38.993
thanks help.
the problem sequence of statements in code such check loop's exit condition not reached until after second input requested. add check -1
it's entered, , break out loop. alternatively, ask miles entered ahead of gallons.
for (;;) { /* "forwver" loop; break out middle */ tanks += 1; miles_per_gallon = (float)miles / gallons; average = average + miles_per_gallon; printf("the miles / gallon tank %.3f\n", miles_per_gallon); printf("enter gallons used (-1 end): "); scanf("%f", &gallons); /* break loop: */ if (gallons == -1) return 0; printf("enter miles driven: "); scanf("%d", &miles); }
Comments
Post a Comment