三候選人 A、B、C,N 人投票(字符串,大小寫不敏感),非 ABC 字符視為棄權。按得票數降序輸出候選人字母與票數,票數相同按字母序輸出。
count['A']、count['B']、count['C']#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct {
char name;
int votes;
} Candidate;
int cmp(const void *a, const void *b) {
Candidate *p1 = (Candidate *)a;
Candidate *p2 = (Candidate *)b;
if (p1->votes != p2->votes)
return p2->votes - p1->votes; // 票數降序
return p1->name - p2->name; // 字母升序
}
int main(void) {
int n;
scanf("%d", &n);
getchar(); // 吸收換行
Candidate c[3] = {{'A',0}, {'B',0}, {'C',0}};
char ch;
for (int i = 0; i < n; i++) {
ch = getchar();
ch = toupper(ch);
if (ch >= 'A' && ch <= 'C')
c[ch - 'A'].votes++;
}
qsort(c, 3, sizeof(Candidate), cmp);
for (int i = 0; i < 3; i++)
printf("%c %d\n", c[i].name, c[i].votes);
return 0;
}
toupper() 統一大小寫,ctype.hch - 'A' 更新計數,無需多重 ifqsort + 比較函數實現多關鍵字排序,代碼簡潔可擴展max/min 函數繁瑣且易錯,排序邏輯硬編碼難維護a[1000] 讀取時 i<=n 可能越界(應 i<n)|| 判斷,toupper 更優雅)輸入: 6 abcA1b 輸出: A 2 B 2 C 1