CS50 Pset1 Cash代码返回异常大数值,函数实现问题求助
CS50 Pset1 找零计算异常问题修复
你的代码输出超大随机数值的核心原因有两个,同时还有一个小的输出错误,具体如下:
错误1:计数变量未初始化
在calculate_quarters、calculate_dimes、calculate_nickels、calculate_pennies这四个计算函数中,你声明了int n;但没有将其初始化为0。C语言中局部变量默认不会被自动初始化,会保留内存中的随机垃圾值,后续的n++操作就是在这个垃圾值的基础上累加,最终返回的自然是毫无意义的超大数字。
错误2:while循环条件逻辑颠倒
以calculate_quarters为例,你写的循环条件是while (cents <= 25),这完全搞反了逻辑——我们需要在剩余美分数大于等于25时,才继续兑换硬币、计数并减去对应面值,正确的条件应该是while (cents >= 25)。其他三个计算函数的循环条件也存在同样的错误。
额外小问题:输出对象错误
在main函数的最后,你写的是printf("%i", quarters);,这只会打印25美分硬币的数量,而作业要求打印的是总硬币数coins,需要修正为printf("%i\n", coins);
修正后的完整代码
#include <cs50.h> #include <stdio.h> int get_cents(void); int calculate_quarters(int cents); int calculate_dimes(int cents); int calculate_nickels(int cents); int calculate_pennies(int cents); int main(void) { // Ask how many cents the customer is owed int cents = get_cents(); // Calculate the number of quarters to give the customer int quarters = calculate_quarters(cents); cents = cents - quarters * 25; // Calculate the number of dimes to give the customer int dimes = calculate_dimes(cents); cents = cents - dimes * 10; // Calculate the number of nickels to give the customer int nickels = calculate_nickels(cents); cents = cents - nickels * 5; // Calculate the number of pennies to give the customer int pennies = calculate_pennies(cents); cents = cents - pennies * 1; // Sum coins int coins = quarters + dimes + nickels + pennies; // Print total number of coins to give the customer printf("%i\n", coins); } int get_cents(void) { int owed; do { owed = get_int("Change owed: "); } while (owed <= 0); return owed; } int calculate_quarters(int cents) { int n = 0; // 初始化计数变量为0 while (cents >= 25) // 修正循环条件 { n++; cents = cents - 25; } return n; } int calculate_dimes(int cents) { int n = 0; while (cents >= 10) { n++; cents = cents - 10; } return n; } int calculate_nickels(int cents) { int n = 0; while (cents >= 5) { n++; cents = cents - 5; } return n; } int calculate_pennies(int cents) { int n = 0; while (cents >= 1) { n++; cents = cents - 1; } return n; }
另外,你提到把循环直接放在main里能正常运行,大概率是因为你在main中手动将计数变量初始化为0,并且用对了循环条件,所以逻辑是正确的;但放到函数里时,遗漏了初始化操作,同时写错了循环条件,才导致异常。
内容的提问来源于stack exchange,提问作者Yassir MAMODBAKAR
相关产品推荐
相关产品推荐

