CS50入门课程Lab1:人口增长计算程序无输出问题求助
CS50 Lab1 人口增长程序无输出问题排查
嘿,我一眼就看到你代码里的关键问题了——提前的return语句直接终止了程序,导致后面的计算和打印逻辑根本没机会执行!咱们来一步步拆解问题:
核心错误分析
提前返回导致程序终止:在你获取完起始和目标人口后,写了这两行:
return start; return end;在C语言里,
main函数里的return语句会直接结束整个程序。所以程序刚拿到用户输入,就直接退出了,后面的年份计算和结果打印代码完全没被执行,这就是你看不到输出的原因。次要错误:换行符拼写错误:最后printf里的
%i/n应该是%i\n,\n才是正确的换行转义字符,/n会被当成普通字符输出。
修正后的代码
#include <cs50.h> #include <stdio.h> // Determine the number of years required for the population to grow from the start size to the end size. int main(void) { // Prompt for start size. Has to be greater than 9, otherwise ask again. // Prompt for end size int start; int end; int years = 0; int n; do { start = get_int("Give me a start size of the population: "); end = get_int("Give me a end size of the population: "); } while (start < 9 || end < start); // Calculate number of years until we reach threshold // 注意:如果起始人口已经等于目标,不需要计算,years保持0 while (start < end) { n = start + (start / 3) - (start / 4); start = n; years++; } // Print number of years printf("The number of years to reach your end population is %i\n", years); // main函数正常结束返回0 return 0; }
额外优化说明
- 我把计算部分的
do-while改成了while循环,因为如果起始人口已经等于目标人口,do-while会多执行一次计算,导致years变成1,这不符合逻辑。用while循环可以避免这种情况。 - 最后
main函数返回0是C程序的标准写法,表示程序正常结束。
这样修改后,程序就能正常计算并输出所需年份了!
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

