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

C++入门答疑:如何实现程序循环运行4次,逐次输入计算商品总成本

C++ 循环录入商品程序修改说明

现有代码存在两处可调整的问题:

  • 循环次数不符合要求:当前for (int a = 0; a < 5; a++)的条件会触发5次循环,如需循环4次,将条件修改为a < 4即可
  • 输出无分隔导致视觉异常:每轮计算结果输出后未添加换行符,多轮输出会拼接在同一行,看起来像程序未正常运行,只需在输出总成本的语句末尾添加换行符\n分隔即可

修改后可正常运行的完整代码

#include <iostream>
using namespace std;

int main()
{
    string Item;
    float Cost;
    float Discount;
    float TotalCost;

    for (int a = 0; a < 4; a++)
    {
        cout << "第" << a + 1 << "轮商品录入\n";
        cout << "What is the item? \n";
        cin >> Item;

        cout << "What is the cost? \n";
        cin >> Cost;

        cout << "What is the discount? \n";
        cin >> Discount;

        TotalCost = Cost - Discount;

        cout << Item << "'s Total Cost is " << TotalCost << "\n\n";
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:54:03