You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50美洲驼种群计算实验问题:初始与终止数量相同时结果错误

解决CS50美洲驼种群计算的年份统计错误问题

你的问题核心在于do-while循环的执行逻辑:do-while会先执行一次循环体,再判断终止条件。当起始规模和终止规模相等时,循环还是会执行一次year++,导致输出多了1年。

修复方案:改用while循环(最简洁的方式)

把原来的do-while循环换成while循环,先判断条件再执行循环体,这样当起始规模已经等于终止规模时,循环根本不会触发,年份保持0:

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

int main(void)
{
    int start ;
    do
    {
        start = get_int("start size: ");
    }
    while (start < 9);

    int end;
    do
    {
        end = get_int("end size: ");
    }
    while (end < start);

    int year = 0;
    // 先判断是否需要计算下一年,再执行循环体
    while (start < end)
    {
        start = start + (start / 3) - (start / 4);
        year++;
    }

    printf("Years: %i", year);
}

另一种可选方案(保留do-while的调整)

如果一定要保留do-while结构,可以在循环体开头先判断是否已经满足条件,直接跳出循环避免更新年份:

int year = 0;
do
{
    if (start >= end)
    {
        break;
    }
    start = start + (start / 3) - (start / 4);
    year++;
}
while (start < end);

两种方案都能解决问题,第一种更符合这个场景的逻辑,代码也更简洁。

内容的提问来源于stack exchange,提问作者kyukwnag94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:30:55