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

澳元模块化找零程序输出全0问题排查求助

嘿,我帮你找出了程序所有硬币数量显示为0的问题,咱们一步步拆解来看:

核心问题分析

你的程序之所以所有硬币数量都是0,是因为几个关键逻辑和语法错误叠加导致的:

  • main函数参数完全错误
    标准C语言里,main函数的正确签名要么是int main(void)(无参数),要么是int main(int argc, char *argv[])(用于命令行参数)。你写的int main(int input)完全不符合规范,这个input变量根本没有被赋值为用户输入的金额——在你的运行环境里它恰好是0,这就导致后续所有硬币计算都是0 / 面额,结果自然全是0。

  • 完全忽略了用户的输入
    你调用了GetChange()来获取用户输入的金额,但没把这个函数的返回值存到任何变量里,反而错误地用了main里那个无效的input参数,等于白做了输入步骤。

  • GetNewChange函数逻辑错得离谱
    你现在的写法是newchange = cents - coin,这只是减去了一枚硬币的面额,而不是该面额硬币的总价值。比如输入100的话,50分硬币应该是2枚,剩余金额应为0,但你的函数会返回100-50=50,后续计算全乱套。正确的逻辑应该是用取模运算cents % coin,或者cents - (GetCoins(cents, coin) * coin),这样才能得到扣除对应硬币后的剩余金额。

  • 没更新剩余金额
    就算GetNewChange是对的,你调用它之后也没把返回值赋值给原来的金额变量,导致每次算下一种硬币时,还是用的初始无效值,根本没用到扣除后的剩余金额。

修正后的完整代码

#include <stdio.h>
#include <stdlib.h> // 引入system函数需要的头文件

void PrintDisplay(void) { 
    printf("Enter an amount to calculate change: "); 
} 

int GetChange(void) { 
    int change; 
    scanf("%d%*c", &change); 
    return change; 
} 

int GetCoins(int cents, int coin) { 
    return cents / coin; 
} 

int GetNewChange(int cents, int coin) { 
    // 用取模运算直接得到剩余金额,高效又准确
    return cents % coin; 
} 

void PrintResult(int fifties, int twenties, int tens, int fives) { 
    printf("The amount of each coin denomination you should give are: \n"); 
    printf("Fifty cent coins: %d \n", fifties); 
    printf("Twenty cent coins: %d \n", twenties); 
    printf("Ten cent coins: %d \n", tens); 
    printf("Five cent coins: %d \n", fives); 
} 

int main(void) { 
    int amount; // 专门存用户输入的金额
    int FiftyCentAmount; 
    int TwentyCentAmount; 
    int TenCentAmount; 
    int FiveCentAmount; 

    PrintDisplay(); 
    amount = GetChange(); // 把用户输入存下来,这步至关重要!

    // 依次计算每种硬币数量,同时更新剩余金额
    FiftyCentAmount = GetCoins(amount, 50); 
    amount = GetNewChange(amount, 50); 

    TwentyCentAmount = GetCoins(amount, 20); 
    amount = GetNewChange(amount, 20); 

    TenCentAmount = GetCoins(amount, 10); 
    amount = GetNewChange(amount, 10); 

    FiveCentAmount = GetCoins(amount, 5); 

    PrintResult(FiftyCentAmount, TwentyCentAmount, TenCentAmount, FiveCentAmount); 
    system("pause"); 
    return 0; 
}

修正要点说明

  1. 把main函数改成了标准的int main(void),去掉了无效的input参数。
  2. 新增了amount变量来存储用户输入的金额,确保所有计算都基于正确的值。
  3. 修复了GetNewChange的逻辑,用取模运算准确计算剩余金额。
  4. 每次算完一种硬币后,立刻把amount更新为剩余金额,保证下一次计算用的是最新值。
  5. 加了#include <stdlib.h>,不然system("pause")可能编译不过。

现在你运行这个修正后的程序,输入5-95之间的金额(比如65),就能得到正确的硬币数量啦:1枚50分、0枚20分、1枚10分、1枚5分,完全符合最优找零逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:07:16