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

C语言统计输入价格分类数量的程序运行异常如何修复?

代码修改方案

原代码核心问题

  • 计数变量hiprc、avgprc、loprc未初始化,初始值为随机垃圾值
  • input未初始化就用于while循环判断,第一次循环逻辑不可控
  • 区间判断逻辑放在了循环外,仅判断了终止输入的-99,没有统计每一次有效输入的价格
  • 终止输入的-99被计入总金额sum和总数量count,导致平均值计算错误
  • 价格区间判断条件逻辑错误,缺少区间边界的正确判断
  • 平均值变量avg为整型,用%.2f输出会出现类型不匹配的错误
  • 输出计数的printf语句缺少对应占位符,无法正常输出统计值

修正后完整代码

#include <stdio.h>

int main () {
    int input = 0;
    int sum = 0;
    int count = 0;
    // 初始化三个分组计数器为0
    int hiprc = 0, avgprc = 0, loprc = 0;
    double avg;

    while (1) {
        printf("Enter the price (-99 to stop): ");
        scanf("%d", &input);
        // 遇到终止符直接退出循环,不计入统计
        if (input == -99) {
            break;
        }
        sum += input;
        count++;
        // 每次输入后判断所属区间,对应计数器+1
        // 区间规则:高价≥85,中价60≤价格≤84,低价<60,可按需调整
        if (input >= 85) {
            hiprc++;
        } else if (input >= 60) {
            avgprc++;
        } else {
            loprc++;
        }
    }
    // 防止用户未输入有效价格导致除0错误
    if (count == 0) {
        printf("No valid price entered.\n");
        return 0;
    }
    // 计算浮点型平均值,避免整数除法截断小数
    avg = (double)sum / count;
    // 按要求格式输出
    printf("High prices: %d\n", hiprc);
    printf("Average Prices: %d\n", avgprc);
    printf("Low Prices: %d\n\n", loprc);
    printf("The average price is: %.2f\n", avg);
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:36:03