2016-10-10 29 views
1

我被分配了一個C程序,以獲得用戶輸入多少額外的水將被添加到一個魚缸,並在24小時後,魚將「BBQ'd」。我遇到的問題是如果我在scanf中輸入一個更高的數字,然後輸入10。循環重複並且永遠給出相同的輸出。我是否使用scanf的正確佔位符?如果用戶輸入的數字高於10,程序爲什麼會循環輸出相同的輸出?

#include <stdio.h> 

int main(void) { 

    //Declares variables 
    double fishTank = 500; 
    int hours = 0; 
    int addWater; 
    //asks user for input. 
    printf("Please enter additional water to be added per hour:"); 
    scanf("%d", &addWater); 

    //while fishtank is greater then or equal to 100 it will run this loop 
    while (fishTank >= 100) { 
     fishTank = fishTank - (fishTank * .1) + addWater; 
     printf("The tank still has %f gallons remaining\n", fishTank); 

     //increments hours by 1 
     hours = hours + 1; 
    } 
    //if hours drops below 24 it will print this output 
    if (hours < 24) { 
     printf("Out of water at hour %d when remaining gallons were %f\n", hours, fishTank); 
    } 
    //if hours is greater then 24 by the time the loop ends it will print this. 
    else if (hours >= 24) { 
     printf("Get out the BBQ and lets eat fish.\n"); 
    } 
    system("pause"); 
    return 0; 
} 

回答

1

看看方程式

fishTank = fishTank - (fishTank * .1) + addWater; 

如果在開始fishTank> 100(fishTank * .1)不能減少fishTank如果addWater> = 10,因爲一些迭代後fishTank * 0.1變得等於addWater

我想,你的解決方案是正確的,但你應該提供一個循環的替代方式。例如,改變條件while作爲

while (hours <= 24 && fishTank >= 100) 
0

罐失去10%的它的當前體積每小時,而如果它具有100個單位爲10個單位。無論用戶輸入什麼都可以獲得。如果這個數字大於10,那麼每次它可以降到100以下時,它就可以再次達到100以上。即使回來正好100,增加10個或更多,就足以讓它有 - 所以它永遠循環

你while語句必須是:

while (fishTank >= 100 && hours < 24) { 
相關問題