簡體   English   中英

如果用戶輸入一個大於 10 的數字,為什么程序會循環相同的輸出?

[英]Why does the program loop the same output if the user inputs a number higher then 10?

我被分配了一個 C 語言程序來讓用戶輸入多少額外的水將添加到魚缸中,24 小時后魚將被“燒烤”。 我遇到的問題是,如果我在 scanf 中輸入的數字大於 10。 循環重復並永遠給出相同的輸出。 我是否為 scanf 使用了正確的占位符?

#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;
}

看方程

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

如果在開始時fishTank > 100(fishTank * .1)如果addWater >= 10 就不能減少fishTank ,因為經過一些迭代之后fishTank * 0.1變得等於addWater

我想,您的解決方案是正確的,但您應該提供一種替代方法。 例如,將while的條件更改為

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

坦克每小時損失其當前體積的 10%,如果它有 100 個單位,則為 10 個單位。 它獲得用戶輸入的任何內容。 如果這個數字大於 10,每次它可能會降到 100 以下,它就會獲得足夠的收益,再次超過 100。 即使它准確地回到 100,添加 10 或更多也足以讓它保持在那里——所以它永遠循環

你的 while 語句需要是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM