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

C语言GPA计算器无法返回对应成绩等级问题求助

C语言GPA计算程序成绩等级输出异常修复方案

问题核心错误点

  • 字符赋值错误:给char类型的grade[x]赋值时使用了双引号包裹的字符串(如"A"),双引号在C中表示字符串字面量,实际返回的是字符串的内存地址,强制转为char类型后就会出现随机乱码字符,应该使用单引号包裹单个字符(如'A')
  • 课程代码数组定义错误:char C_code[12][6][a]为不必要的三维数组,你需要存储a门课程的长度最大为6的课程代码,只需定义二维数组char C_code[a][7]即可(多1位存储字符串结束符\0)
  • 课程代码读取参数错误:scanf("%6s", &C_code[x])中C_code[x]本身就是数组首地址,不需要再加取地址符&

修复后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

float gpa_ICT(int a){
    float point[a], unit[a], score[a];
    char C_code[a][7]; // 修正数组定义:a门课,每门课程代码最长6个字符+1位结束符
    char grade[a];

    //读取课程代码、分数、学分
    for(int x = 0; x < a; x++){
        printf("Enter Course Code: ");
        scanf("%6s", C_code[x]); // 修正取地址符
        printf("Enter course score: ");
        scanf("%f", &score[x]);
        printf("Enter course unit: ");
        scanf("%f", &unit[x]);

        //根据分数赋值绩点和等级
        if(score[x] >= 70){
            grade[x]= 'A'; // 修正为单引号字符
            point[x] = 5;
        }
        else if (score[x] >= 60 && score[x] <=69){
            grade[x]= 'B';
            point[x] = 4;
        }
        else if (score[x] >= 50 && score[x] <=59){
            grade[x]= 'C';
            point[x] = 3;
        }
        else if (score[x] >= 45 && score[x] <=49){
            grade[x]= 'D';
            point[x] = 2;
        }
        else if (score[x] <=44){
            grade[x]= 'F';
            point[x] = 0;
        }
        else{
           printf("ERROR!");
        }
    }

    //逐门课程输出代码和对应等级
    for(int i = 0; i < a; i++){
        printf("%s : %c\n",C_code[i] ,grade[i]);
    }

    //计算总绩点
    float sum = 0;
    float Total;
    for(int y = 0; y < a; y++){
        Total = point[y]*unit[y];
        sum = sum + Total;
    }

    //计算总学分
    float totalUnit = 0;
    for(int z = 0; z < a; z++){
        totalUnit = totalUnit + unit[z];
    }

    //计算GPA
    float GPA = sum / totalUnit;
    return GPA;
}

int main()
{
    int course;
    printf("How many courses? ");
    scanf("%d", &course);

    float result = gpa_ICT(course);
    printf("Your GPA is %0.2f", result);
    return 0;
}

修复后对应测试用例输出

How many courses? 3
Enter Course Code: MTS202
Enter course score: 75
Enter course unit: 3
Enter Course Code: ICT202
Enter course score: 58
Enter course unit: 2
Enter Course Code: MEE202
Enter course score: 65
Enter course unit: 2
MTS202 : A
ICT202 : C
MEE202 : B
Your GPA is 4.14

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:15:03