2014-06-24 45 views
1

我正在做一本書中的以下程序,不明白我在哪裏出錯。有人能向我指出我失蹤的邏輯錯誤嗎?有人可以向我指出一個小邏輯錯誤嗎?

開發一個程序,該程序將輸入每輛坦克所使用的行駛里程和加侖數。 程序應該計算並顯示每個加侖獲得的每加侖英里數。處理完所有輸入信息後,程序應計算並打印所有油罐車獲得的每加侖組合英里數。

#include <stdio.h> 

int main(void) { 
    int total = 0, count = 0; 
    float gallons_used, mpg, miles; 
    while(gallons_used != -1) { 
    printf("Enter the gallons used (-1 to end): "); 
     scanf("%f", &gallons_used); 
     printf("Enter the miles driven: "); 
     scanf("%f", &miles); 
     mpg = miles/gallons_used; 
     printf("Miles/gallon for this tank was %f\n", mpg); 
     total += mpg; 
     count++; 
    } 
    total /= count; 
    printf("Average miles to the gallon was: %d\n", total); 
    return 0; 
} 

現在看來,我有循環恰到好處,直到點我值爲-1退出,因爲它仍要求該艙的里程,顯然它輸入完全拋出了總數在最後。

+0

這是因爲你不讀取用戶加侖後才退出。在此之後放置一個break語句而不是while條件。 –

+1

您檢查'gallons_used'的值,但您從未初始化它!如果它恰好從值「-1」開始呢? – abelenky

+0

或者至少只是檢查'gallons_used <0',如果是的話,跳出循環 –

回答

1
while(true) { 
printf("Enter the gallons used (-1 to end): "); 
    scanf("%f", &gallons_used); 
    printf("Enter the miles driven: "); 
    scanf("%f", &miles); 
    if(gallons_used== -1)break; 
    mpg = miles/gallons_used; 
    printf("Miles/gallon for this tank was %f\n", mpg); 
    total += mpg; 
    count++; 
} 
+0

timmy的回答是更好它不要求英里,如果你輸入-1加侖:) – ETFovac

+0

這個答案工作,謝謝! – user3765259

2

你可以用一個無限循環,並打破它,以防萬一gallons_used = -1

for(;;) { // <-- infinite loop 
    printf("Enter the gallons used (-1 to end): "); 
    scanf("%f", &gallons_used); 
    if (gallons_used == -1) 
     break; // <-- exit the loop 
    printf("Enter the miles driven: "); 
    scanf("%f", &miles); 
    mpg = miles/gallons_used; 
    printf("Miles/gallon for this tank was %f\n", mpg); 
    total += mpg; 
    count++; 
} 
+0

這也不起作用,它和以前一樣,它仍然要求上次輸入。 – user3765259

+2

@ user3765259:要求輸入,但如果它是-1,所以它應該工作 – StackOverflower

0
#include <stdio.h> 

int main(void) { 
    int total = 0, count = 0; 
    float gallons_used, mpg, miles; 
    while(gallons_used != -1) { 
    printf("Enter the gallons used (-1 to end): "); 
     scanf("%f", &gallons_used); 
     if (gallons_used < 0)    // check gallons_used 
      break; 
     printf("Enter the miles driven: "); 
     scanf("%f", &miles); 
     mpg = miles/gallons_used; 
     printf("Miles/gallon for this tank was %f\n", mpg); 
     total += mpg; 
     count++; 
    } 
    total /= count; 
    printf("Average miles to the gallon was: %d\n", total); 
    return 0; 
} 
0

您正在使用gallons_used初始化。使用未初始化的變量調用未定義的行爲。您需要先對它進行初始化,然後再比較while的條件表達式。你可以這樣做

printf("Enter the gallons used (-1 to end): "); 
scanf("%f", &gallons_used);   // Reading value for gallons_used 

while(gallons_used != -1) { 
    printf("Enter the miles driven: "); 
    scanf("%f", &miles); 
    mpg = miles/gallons_used; 
    printf("Miles/gallon for this tank was %f\n", mpg); 
    total += mpg; 
    count++; 
    printf("Enter the gallons used (-1 to end): "); 
    scanf("%f", &gallons_used); 
} 
相關問題