生活随笔
收集整理的這篇文章主要介紹了
结构体对成绩进行排名
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
期末考試結束后要對同學們的考試成績進行排序,張老師已經計算好了每一位同學的總成績。請編寫程序,輸入每位同學的總成績并輸出一個按成績高低排列的名次表。
該問題中,在成績排序的同時,需要相應的學號和姓名一起隨之變化。因此,我們可以使用結構體,學號、姓名、成績以及名次作為結構體成員。通過對結構體對象成員(總成績)的大小判斷,實現把結構體對象作為一個整體進行排序操作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>typedef struct student //聲明結構體 student
{ char id[5]; //學生學號(四位)char name[40]; //學生姓名float score; //期末總成績int num; //名次
}student; int main(int argc, char *argv[])
{student stu[100], temp; //定義結構體對象數組 stu 和臨時對象 tempint i, j, n;printf("輸入學生人數(1~100):");scanf("%d", &n);printf("-----------------------\n");for(i = 0; i < n; i++) { //輸入學生成績printf("學號輸入9999則停止輸入!\n");printf("學號(9999):"); scanf("%s", stu[i].id);if(strcmp(stu[i].id, "-1") == 0) {n = i;break;}printf("姓名:"); scanf("%s", stu[i].name);printf("總成績:"); scanf("%f", &stu[i].score);}for(i = 0; i < n; i++) { //按成績排序(冒泡法)for(j = i+1; j < n; j++) {if(stu[i].score < stu[j].score) {temp = stu[i];stu[i] = stu[j];stu[j] = temp;} //結構體變量整體交換}stu[i].num = i+1;}printf("----------------------------------\n");printf(" 學號 姓名 成績 名次\n");for(i = 0;i < n; i++) { //輸出名次printf("%6s",stu[i].id);printf("%10s",stu[i].name);printf("%12.2f",stu[i].score);printf("%6d\n",stu[i].num);} return 0;
}
運行結果:
?
總結
以上是生活随笔為你收集整理的结构体对成绩进行排名的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。