CS50 Lab1羊驼种群计算C程序接收输入但无输出问题排查
CS50 Lab1 羊驼种群计算程序问题
问题说明
编写的C程序可正常接收输入,但无法输出结果。背景规则:初始种群为n只羊驼,每年出生n/3只新羊驼,死亡n/4只羊驼。例如初始n=1200时,年末种群为1200+400-300=1300只。
程序代码
#include <math.h> #include <stdio.h> int main(void) { // TODO: Prompt for start size int a, b; do { printf("Start Size: "); scanf("%i", &a); } while (a < 9); // TODO: Prompt for end size do { printf("End Size: "); scanf("%i", &b); } while (b < a); // TODO: Calculate number of years until we reach threshold int y = 0; while (a < b) { a = round((float)a + (a / 4) - (a / 3)); y++; } // TODO: Print number of years printf("Years: %i ", y); }
测试用例
- 输入:起始数量1200,结束数量1300;预期输出:
Years: 1 - 输入:起始数量依次输入-5、3、9,结束数量依次输入5、18;预期输出:
Years: 8 - 输入:起始数量20,结束数量依次输入1、10、100;预期输出:
Years: 20 - 输入:起始数量100,结束数量1000000;预期输出:
Years: 115
问题分析与修复
核心错误
- 种群计算逻辑颠倒:题目明确每年出生数量为
a/3,死亡数量为a/4,但代码中错误地写成了(a/4) - (a/3),导致种群数量逐年减少。当起始数量a小于目标数量b时,循环会无限执行(a越来越小,永远达不到b),程序因此无法输出结果。 - 输出格式错误:
printf语句中的换行符写法错误,应使用\n而非直接换行。
修复后的代码
#include <math.h> #include <stdio.h> int main(void) { int a, b; // 输入起始种群数量 do { printf("Start Size: "); scanf("%i", &a); } while (a < 9); // 输入目标种群数量 do { printf("End Size: "); scanf("%i", &b); } while (b < a); int years = 0; while (a < b) { // 正确计算种群变化:当前数量 + 出生数量 - 死亡数量 a = round((float)a + (a / 3.0) - (a / 4.0)); years++; } printf("Years: %i\n", years); return 0; }
额外优化
将a/3和a/4改为a/3.0和a/4.0,确保浮点运算的精度,避免整数除法导致的计算误差。
内容的提问来源于stack exchange,提问作者Tejash
相关产品推荐
相关产品推荐

