You need to enable JavaScript to run this app. C语言实现贪心找零算法程序运行无输出问题咨询(CS50第二周)
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现贪心找零算法程序运行无输出问题咨询(CS50第二周)

问题根因与排查方向

直接导致程序无输出的核心语法问题

C语言中,if、while等流程控制语句如果没有用花括号包裹执行块,仅会对紧随其后的单条语句生效。你当前代码的所有循环结构都没有写花括号,会直接造成逻辑错位,甚至触发无限死循环:
以第一个循环为例,你写的代码:

while (cents > q)
    coins_used = (cents / q);
cents = (cents % q);

实际执行逻辑等价于:

while (cents > q) {
    // 仅这一句属于循环,cents的值永远不会在循环内改变
    coins_used = (cents / q);
}
// 下面的取余代码永远不会被执行,程序卡在循环中无输出
cents = (cents % q);

其余需要修正的逻辑错误

  • 硬币面值定义错误:作业要求的10美分硬币(dime)实际值为10,你当前写的d = 20不符合题目规则
  • 剩余金额计算错误:统计完单种面值的硬币数量后,应该用cents = cents % 当前面值计算剩余待找零金额,你写的cents = cents + (cents % 当前面值)属于加法逻辑,会导致剩余金额越算越大,永远无法归零
  • 循环判断边界错误:你写的循环判断是cents > 当前面值,会漏掉剩余金额刚好等于硬币面值的场景(比如剩余25美分时,25 >25为假,无法统计这枚25分硬币),正确判断应为cents >= 当前面值
  • 输出逻辑错误:你当前每计算完一种面值就判断是否归零并打印,会造成多次重复输出,正确逻辑是按从大到小的面值顺序完成所有硬币计数后,统一打印最终结果
  • 计数赋值错误:第一次统计25分硬币时,你写的是直接给coins_used赋值,后续统计才用累加,虽然第一次赋值不会造成数值错误,但累加式写法更统一,可避免后续修改引入问题

可参考的修复后代码结构

#include <cs50.h>
#include <math.h>
#include <stdio.h>

int main(void) {
    int coins_used = 0;
    float owed_to_customer;
    int q = 25;
    int d = 10;
    int n = 5;
    int p = 1;

    // 获取合法非负输入的逻辑保持不变
    do {
        owed_to_customer = get_float("How much is owed?: \n");
    } while (owed_to_customer < 0);

    int cents = round(owed_to_customer * 100);

    // 用花括号明确每个循环的执行范围
    while (cents >= q) {
        coins_used += cents / q;
        cents = cents % q;
    }

    while (cents >= d) {
        coins_used += cents / d;
        cents = cents % d;
    }

    while (cents >= n) {
        coins_used += cents / n;
        cents = cents % n;
    }

    while (cents >= p) {
        coins_used += cents / p;
        cents = cents % p;
    }

    printf("%d\n", coins_used);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 19:06:03