CS50美洲驼种群计算C代码运行中断无输出问题求助
问题分析与修复方案
核心问题
你的代码在种群增长计算逻辑上存在错误,导致可能进入死循环,程序一直卡在循环里无法输出结果。
当前的计算逻辑:
start_size = start_size + (start_size/3); // 先增加当前种群的1/3 start_size = start_size - (start_size/4); // 再减去新种群的1/4
这是错误的——题目中种群变化规则是:每年新增数量为年初种群数的1/3,死亡数量为年初种群数的1/4。你现在的第二步是基于增长后的数量计算减少量,导致实际增长远低于预期,甚至可能出现种群数量不再增长的情况,永远达不到目标值,程序就会无限循环。
修复后的代码
正确的做法是基于同一初始值计算当年的出生数和死亡数,再更新种群数量:
#include <cs50.h> #include <stdio.h> int main(void) { // 输入初始种群数量 int start_size; do { start_size = get_int("enter the start size\n"); } while (start_size < 9); // 输入目标种群数量 int end_size; do { end_size = get_int("enter the end size\n"); } while (end_size < start_size); // 计算所需年数 int years = 0; int current_size = start_size; // 用临时变量跟踪种群变化,避免修改初始输入 do { int born = current_size / 3; int died = current_size / 4; current_size = current_size + born - died; years++; } while (current_size < end_size); // 输出结果 printf("the needed number of years is: %i\n", years); }
关键修改点
- 用临时变量
current_size跟踪种群变化,逻辑更清晰,也避免误改初始输入值。 - 基于同一个
current_size计算当年的出生数和死亡数,严格符合题目中的种群增长规则。 - 修复后种群数量会正常增长,不会出现无限循环,程序能正常输出结果。
如果用scanf替换get_int,只需把get_int("提示文本")替换为scanf("%d", &变量名)即可,但核心问题始终是计算逻辑错误,和输入函数无关。
内容的提问来源于stack exchange,提问作者saso yoo
相关产品推荐
相关产品推荐

