首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言初學者常見錯誤:結構體參數、函數原型位置、型別不匹配全面解析

     編輯:程式設計綜合問答

原代碼主要問題

  1. 函數原型宣告放在 main 內部:應置於全域或頭文件。
  2. 參數列寫 struct Student stu[]:C 語言中參數只需寫 Student stu[] 或 Student *stu(需 typedef)。
  3. 函數定義與宣告型別不一致:max 回傳 struct Student 但實參為指標。
  4. 迴圈條件寫錯:for (i = 0; i if (stu[i].aver > stu[m].aver) 缺少條件與大括號。
  5. scanf 格式字串與引數不符:缺少 & 取址符。

修正版骨架


#include 
#define N 3

typedef struct {
    int num;
    char name[20];
    float score[3];
    float aver;
} Student;

void input(Student stu[]);
Student max(Student stu[]);
void print(Student s);

int main() {
    Student stu[N];
    input(stu);
    print(max(stu));
    return 0;
}

void input(Student stu[]) {
    for (int i = 0; i < N; i++) {
        scanf("%d %19s %f %f %f", &stu[i].num, stu[i].name,
              &stu[i].score[0], &stu[i].score[1], &stu[i].score[2]);
        stu[i].aver = (stu[i].score[0] + stu[i].score[1] + stu[i].score[2]) / 3.0f;
    }
}

Student max(Student stu[]) {
    int m = 0;
    for (int i = 1; i < N; i++)
        if (stu[i].aver > stu[m].aver) m = i;
    return stu[m];
}

void print(Student s) {
    printf("\n成績最高的學生是:\n學號:%d\n姓名:%s\n成績:%.1f,%.1f,%.1f\n平均:%.2f\n",
           s.num, s.name, s.score[0], s.score[1], s.score[2], s.aver);
}

建議初學者先掌握基本語法、函數傳參、結構體用法,再嘗試完整程式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved