輸入若干成績(0-100),負數結束。統計各分數段人數並按格式輸出:0~39: **40~49: **
...90~100: **
#include <iostream>
#include <string>
using namespace std;
int main() {
int cnt[11] = {0}; // 索引 0-10 對應 0-9,10-19,...,100
int score;
while (cin >> score) {
if (score < 0) break;
if (score > 100) continue; // 可選:忽略非法分數
int idx = score / 10;
if (idx == 10) idx = 10; // 100 歸入第 10 段
else if (idx < 4) idx = 3; // 0-39 合併為第 3 段(索引 3)
cnt[idx]++;
}
const char* labels[] = {"0~39", "40~49", "50~59", "60~69", "70~79", "80~89", "90~100"};
for (int i = 0; i < 7; ++i) {
cout << labels[i] << " " << cnt[i+3] << endl; // 索引 3-9 對應 7 個段
}
return 0;
}
cnt 覆蓋 0-100 全範圍(索引 = 分數/10)。score/10 為 0,1,2,3 統一映射到索引 3。100/10=10,單獨作為索引 10(對應 90-100 段)。labels 對應 7 個展示段,讀取 cnt[3] 到 cnt[9]。若分段邊界可配置,可用 vector 存儲區間,遍歷判斷歸屬,通用性更強。