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

CS50第一周Cash作业计算函数无法返回值问题求助

CS50 Cash作业问题修复方案

你的代码主要有三个核心问题,直接导致计算错误甚至程序卡死:

  • 死循环逻辑错误:所有calculate_*函数里的while循环完全多余,而且没有修改循环依赖的cents变量,只要满足循环条件(比如cents>24),循环就会无限运行,程序直接卡死。实际上贪心算法求最少硬币,直接用整数除法就能得到当前面额的最大可用硬币数,根本不需要循环。
  • 变量未初始化:比如calculate_quarters里的quaters(还拼错了)没有初始值,如果传入的cents<=24,循环不会执行,返回的是内存里的随机垃圾值,导致结果错误。
  • 拼写错误:calculate_quarters里的变量名quaters少写了一个r,应该是quarters。

修复后的完整实现代码如下:

#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 cents;
    do{
        cents = get_int("Change Owed: ");
    }
    while (cents < 0);
    return cents;
}

int calculate_quarters(int cents)
{
    return cents / 25;
}

int calculate_dimes(int cents)
{
    return cents / 10;
}

int calculate_nickels(int cents)
{
    return cents / 5;
}

int calculate_pennies(int cents)
{
    return cents;
}

说明:

  1. 所有calculate_*函数直接返回整数除法的结果,这正是贪心算法的核心:用当前最大面额的硬币尽可能多的数量,保证总硬币数最少。
  2. calculate_pennies直接返回cents即可,因为cents/1等价于cents,更简洁。
  3. 修正了拼写错误,确保变量名正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:17:46