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

为何计算出的总金额为0?C++存钱罐代码问题排查

存钱罐程序总金额始终为0的问题分析

我运行一段C++存钱罐程序时,总金额始终显示为0。该程序应接收paper、coins、cents三类金额输入并计算总金额,代码如下:

int coins = 0;
int paper = 0;
int cents = 0;
int transaction = 0;
int total_money = coins + paper + cents;

cout << "Do you want to fill your piggy bank?";
cin >> transaction;

while (transaction != 2)
{
    cout << "How many paper money? :";
    cin >> paper;
    cout << "How many coins ? :";
    cin >> coins;
    cout << "How many cents? :";
    cin >> cents;
    cout << "Do you want another transaction?";
    cin >> transaction;
    if (transaction == 2)
    {
        cout << "total in piggy bank" << total_money << endl;
    }
    else
    {
        cout << "End of the program";
    }

    return 0;
}

问题点分析

  • 总金额计算时机错误:total_money在变量初始化时就被赋值为0(因为此时coins、paper、cents都是初始的0),后续用户输入新的金额值后,程序不会自动重新计算total_money,所以它的值永远是0。必须在每次用户输入完金额后,重新执行total_money = coins + paper + cents;(如果是累加多次交易,就用total_money += paper + coins + cents;)来更新总金额。
  • 循环提前终止:return 0;写在了while循环的内部,第一次循环执行到这里就会直接退出整个程序,循环根本无法重复执行,用户连一次完整的交易流程都走不完。
  • 分支逻辑混乱:当用户输入的transaction不等于2时,直接输出"End of the program",但此时用户可能想继续交易(比如输入1),这部分逻辑完全不符合需求。正确逻辑应该是:只有当transaction等于2时,计算并显示总金额;否则回到循环开头,进行下一次交易。

修正后的示例代码

#include <iostream>
using namespace std;

int main()
{
    int coins = 0;
    int paper = 0;
    int cents = 0;
    int transaction = 0;
    int total_money = 0;

    cout << "Do you want to fill your piggy bank? (1=Yes, 2=No): ";
    cin >> transaction;

    while (transaction != 2)
    {
        cout << "How many paper money? : ";
        cin >> paper;
        cout << "How many coins ? : ";
        cin >> coins;
        cout << "How many cents? : ";
        cin >> cents;
        // 每次输入后累加计算总金额
        total_money += paper + coins + cents;

        cout << "Do you want another transaction? (1=Yes, 2=No): ";
        cin >> transaction;
    }
    // 退出循环后统一显示总金额
    cout << "Total in piggy bank: " << total_money << endl;
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:25:25