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

如何计算5件商品折后总价格?现有C语言for循环代码仅输出单件折后价

代码修改方案

现有代码已经完成了单件商品的折扣计算逻辑,仅需要新增一个金额累计变量即可实现5件商品折后总金额的统计,改动点如下:

  • 新增sum_total变量,初始值设为0,用于累计所有商品的折后价格
  • 每次计算完单件商品的折后价total后,执行sum_total += total把当前商品金额累加进总金额
  • 5件商品全部计算完成(for循环结束后),输出总金额即可

修改后的完整代码如下:

#include <stdio.h>
int main()
{
    float price1,disc,total,sum_total = 0;
    int i;
    for (i=0;i<5;i++){
        printf("\nEnter price of item : "); // 输入商品单价
        scanf("%f",&price1);
        if(price1<50)
        {
            disc=(price1*10)/100; 
            total=price1-disc; // 计算折后价格
            printf("$Item after discount is: %.2f\n",total);
        }
        else if(price1>=50 && price1<200)
        {
            disc=(price1*20)/100; // 计算折扣
            total=price1-disc; // 计算折后价格
            printf("$Item after discount is: %.2f\n",total);
        }
        else if(price1>=200 && price1<=500)
        {
            disc=(price1*25)/100; // 计算折扣
            total=price1-disc; // 计算折后价格
            printf("$Item after discount is: %.2f\n",total);
        }
        else if(price1>500)
        {
            disc=(price1*30)/100; // 计算折扣
            total=price1-disc; // 计算折后价格
            printf("$Item after discount is: %.2f\n",total);
        }
        sum_total += total; // 累加当前商品折后价到总金额
    }
    printf("\nTotal payable amount for 5 items after discount: %.2f\n", sum_total);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:36:04