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

C 超級排序:學生總分排名輸出前 10 名學號,邏輯錯誤全面修正

     編輯:程式設計綜合問答

原始碼存在四大關鍵錯誤:

  1. s[i] = s[i] - i - 1:莫名扣除學號值,導致總分錯誤。
  2. 找最大值後 s[m[x-1]] = 0:將**學號索引**當分數索引歸零,破壞資料。
  3. m[x] = max:應存學號卻存了分數。
  4. for(i=0;i<=10;i++):輸出 11 筆而非 10 筆。

正確邏輯

  1. 讀入 n, k,建立結構體陣列 Student { id, total }。
  2. 累加各科分數得 total。
  3. 以 total 降序、id 升序排序 (可用 qsort)。
  4. 輸出前 10 筆 id。

修正程式碼

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

typedef struct { int id; int total; } Stu;

int cmp(const void* a, const void* b) {
    Stu* p = (Stu*)a, *q = (Stu*)b;
    if (q->total != p->total) return q->total - p->total;
    return p->id - q->id;
}

int main() {
    int n, k;
    if (scanf("%d %d", &n, &k) != 2) return 0;
    Stu* a = malloc(n * sizeof(Stu));
    for (int i = 0; i < n; ++i) {
        int id, sum = 0, score;
        scanf("%d", &id);
        for (int j = 0; j < k; ++j) { scanf("%d", &score); sum += score; }
        a[i] = (Stu){id, sum};
    }
    qsort(a, n, sizeof(Stu), cmp);
    for (int i = 0; i < 10 && i < n; ++i) {
        if (i) printf(" ");
        printf("%d", a[i].id);
    }
    puts("");
    free(a);
    return 0;
}

使用結構體封裝資料、標準庫排序、正確輸出格式,即可 AC。

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