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

C语言编写的学生成绩统计程序无法运行,故障原因是什么?

错误原因
  • 函数声明与定义、调用逻辑不匹配:前置声明的best_score函数参数类型、数量都和后续定义不符,且all_score函数未做前置声明,C语言要求函数调用前必须有可见的声明或定义。
  • 参数类型不兼容:调用best_score、all_score时传入的是struct student类型的结构体变量,但函数定义的形参要求是float数组,类型完全不匹配,编译器会直接报错。
  • 统计逻辑错误:两个工具函数内部每次调用都会重新初始化max、temp为0,无法完成遍历所有成绩对比取最大值、累加总分的需求。
  • 结果未输出:计算得到的最高分、总分变量是for循环内部的局部变量,循环结束后无法访问,也没有对应的输出语句打印结果。
修复方案

修复后可正常运行的完整代码如下:

#include<stdio.h>
#define SIZE 3

// 前置声明函数,参数为学生结构体数组、数组长度
double best_score(struct student list[], int len);
double all_score(struct student list[], int len);

struct student {
    int number;
    char name[20];
    double grade;
};

int main(){
    struct student list[SIZE];
    int i;
    double max_score, total_score;

    for(i = 0; i < SIZE; i++){
        printf("enter your student ID : ");
        scanf("%d", &list[i].number);
        printf("enter your name : ");
        scanf("%s", list[i].name);
        printf("enter your score : ");
        scanf("%lf", &list[i].grade);
        printf("\n");
    }

    printf("\n===== 学生成绩列表 =====\n");
    for(i = 0; i< SIZE; i++){
        printf("ID: %d, name: %s, score: %.2lf\n", list[i].number, list[i].name, list[i].grade);
    }

    // 传入完整结构体数组计算统计结果
    max_score = best_score(list, SIZE);
    total_score = all_score(list, SIZE);

    printf("\n===== 统计结果 =====\n");
    printf("全体总分:%.2lf\n", total_score);
    printf("最高分:%.2lf\n", max_score);

    return 0;
}

// 遍历所有成绩取最高分
double best_score(struct student list[], int len){
    double max = list[0].grade;
    for(int i = 1; i < len; i++){
        if (max < list[i].grade) {
            max = list[i].grade;
        }
    }
    return max;
}

// 累加所有成绩算总分
double all_score(struct student list[], int len){
    double total = 0;
    for(int i = 0; i < len; i++){
        total += list[i].grade;
    }
    return total;
}

本次修复的核心调整:

  1. 统一了两个工具函数的声明、定义参数类型,适配结构体传参需求,返回值改为double匹配成绩精度
  2. 去掉了循环内重复调用函数的逻辑,改为数据录入完成后一次性传入整个数组计算结果
  3. 补全了统计结果的输出逻辑
  4. 优化了最高分初始值设置逻辑,避免所有成绩为负时结果错误的边界问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:27:03