74 lines
1.7 KiB
C
74 lines
1.7 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
typedef struct game {
|
|
char name[8]; // 參賽者姓名
|
|
int score; // 得分
|
|
} GAME;
|
|
|
|
|
|
int main() {
|
|
GAME *bowling ; // 動態分配記憶體的指標
|
|
int total = 0; // 參賽者數量
|
|
int i , j ,temp;
|
|
char input[32]; // 暫存用來處理輸入
|
|
|
|
printf("請逐筆輸入參賽者的資訊...\n");
|
|
while (1) {
|
|
// 提示輸入參賽者名稱與得分
|
|
printf("輸入第%d位參賽者名字 得分 => ", total + 1);
|
|
|
|
// 讀取一行輸入
|
|
fgets(input, sizeof(input), stdin);
|
|
|
|
// 若按下<Enter>直接結束輸入,結束輸入過程
|
|
if (strcmp(input, "\n") == 0) {
|
|
break;
|
|
}
|
|
|
|
// 動態分配記憶體空間以保存新的參賽者資料
|
|
bowling = (GAME *)malloc( (total + 1) * sizeof(GAME));
|
|
|
|
// printf("分配的記憶體位址: %p\n", (void *)bowling);
|
|
|
|
// 解析輸入的名稱和得分
|
|
sscanf(input, "%s %d", bowling[total].name, &bowling[total].score);
|
|
|
|
total++;
|
|
}
|
|
|
|
// 顯示輸入結果
|
|
|
|
|
|
|
|
printf("\n成績排名\n============\n");
|
|
|
|
for (i=0 ; i<total-1;i++){
|
|
for(j=0 ; j<total-i-1;j++){
|
|
if (bowling[j].score<bowling[j+1].score){
|
|
temp = bowling[j+1].score;
|
|
bowling[j+1].score = bowling[j].score;
|
|
bowling[j].score = temp;
|
|
}
|
|
}
|
|
}
|
|
|
|
for (i = 0; i < total; i++) {
|
|
if(i + 1==1)
|
|
printf("%d. %s %d 冠軍\n", i + 1, bowling[i].name, bowling[i].score);
|
|
else if(i + 1==2)
|
|
printf("%d. %s %d 亞軍\n", i + 1, bowling[i].name, bowling[i].score);
|
|
else if(i + 1==3)
|
|
printf("%d. %s %d 季軍\n", i + 1, bowling[i].name, bowling[i].score);
|
|
else if (i + 1 >3)
|
|
printf("%d. %s %d\n", i + 1, bowling[i].name, bowling[i].score);
|
|
}
|
|
|
|
// 釋放動態記憶體
|
|
free(bowling);
|
|
|
|
return 0;
|
|
}
|
|
|