我被分配了一個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;
}