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

C语言百分比计算器出现未知错误与异常输出,请求问题排查

C语言百分比计算器错误分析与修正

代码中的错误点:

  • scanf传参错误:所有scanf("%d", s1);写法都错误,scanf需要传入变量的地址,应改为scanf("%d", &s1);,直接传变量值会导致程序读写非法内存,引发异常。
  • 百分比计算逻辑错误:5门课总分是500,你用sum/100计算百分比完全错误;且sum是整数、100也是整数,整数除法会截断小数。正确计算应为per = (float)sum / 5;(等价于sum/500.0*100),才能得到正确的百分比数值。
  • printf格式符不匹配:per是float类型,用%d(整数格式符)输出会导致乱码或错误数值,应换成%.2f(保留两位小数)或%f。
  • 字符串中的%未转义:输出文本里的10%、20%等,在printf字符串中需要写成10%%,否则%会被当成格式符处理,导致参数解析错误。
  • 条件判断逻辑漏洞:
    • 第一个条件per>60 && per<70未覆盖等于60或70的情况;
    • 第二个条件per>70.1 && per<90跳过了70到70.1的区间,逻辑不严谨;
    • 应调整为合理区间划分,比如per >=60 && per <70、per >=70 && per <90、per >=90。
  • main函数不符合标准:C标准不推荐void main,应使用int main(),最后加上return 0;。
  • printf语句分号位置不规范:printf("...",per)后面的分号单独写在大括号内,虽语法能通过,但属于不规范写法,应将分号紧跟在printf之后。

修正后的代码:

#include <stdio.h>

int main()
{
    int s1, s2, s3, s4, s5, sum;
    float per;
    
    printf("Enter subject 1 marks out of 100: ");
    scanf("%d", &s1);
    printf("Enter subject 2 marks out of 100: ");
    scanf("%d", &s2);
    printf("Enter subject 3 marks out of 100: ");
    scanf("%d", &s3);
    printf("Enter subject 4 marks out of 100: ");
    scanf("%d", &s4);
    printf("Enter subject 5 marks out of 100: ");
    scanf("%d", &s5);

    sum = s1 + s2 + s3 + s4 + s5;
    per = (float)sum / 5;  // 总分500,除以5直接得到百分比
    
    if (per >= 60 && per < 70) {
        printf("Your percentage is %.2f and you get 10%% scholarship\n", per);
    } else if (per >= 70 && per < 90) {
        printf("Your percentage is %.2f and you get 20%% scholarship\n", per);
    } else if (per >= 90) {
        printf("Your percentage is %.2f and you get 30%% scholarship\n", per);
    } else {
        printf("Your percentage is %.2f and you don't get any scholarship\n", per);
    }
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:01:18