为大输入无限运行的循环

问题描述

我是自学者,我正在研究人口增长问题,当我输入一个我想要达到的大结局数时,我遇到了无限循环的问题。

#include <cs50.h>
#include <stdio.h>

int main(void) {
    // Todo: Prompt for start size
    int n;

    do {
        n = get_int("Enter the starting size of your llamas: ");
    } while (n <= 8);

    // Todo: Prompt for end size
    int j;

    do {
        j = get_int("Enter the Ending size of your llamas: ");
    } while (j <= n);

    // Todo: Calculate number of years until we reach threshold
    int k = 0;

    do {
        n = n + (n/3) - (n/4);
        printf("The number is %i\n",n);
        k++;
    } while (n != j);

    // Todo: Print number of years
    printf("The number is %i\n",k);
}

答案应该是达到最终尺寸美洲驼所需的年数,但我无法输入大量最终尺寸,您能帮我找出问题所在,也许在我的数学中或标志。提前致谢。

解决方法

对于大数,n 在每次迭代中增加的幅度大于 1,因此有可能它变得大于 j 而没有先等于它。

将测试 while(n != j); 更改为 while(n < j);