輸入 10 個整數,輸出僅出現一次的數字(保持原相對順序)。
#include
#include
#include
using namespace std;
int main() {
vector a(10);
for (int& x : a) cin >> x;
unordered_map freq;
for (int x : a) ++freq[x];
cout << "A: "; for (int x : a) cout << x << ' '; cout << '\n';
cout << "B: ";
for (int x : a) if (freq[x] == 1) cout << x << ' ';
cout << '\n';
return 0;
}
時間 $O(n)$,空間 $O(n)$。原題用雙重循環 $O(n^2)$,數據量小時可接受,但哈希表更優雅。
10 位同學成績(0-100),求最高/最低/平均分、最高最低分人數、對應學號(下標)、標準差。
#include
#include
#include
#include
using namespace std;
int main() {
const int N = 10;
vector score(N);
cout << "請輸入 10 位同學成績 (0-100):\n";
for (int i = 0; i < N; ++i) {
cin >> score[i];
// 可選:輸入驗證 while (score[i] < 0 || score[i] > 100) ...
}
double maxS = *max_element(score.begin(), score.end());
double minS = *min_element(score.begin(), score.end());
double sum = accumulate(score.begin(), score.end(), 0.0);
double avg = sum / N;
int maxCnt = 0, minCnt = 0;
vector maxIdx, minIdx;
for (int i = 0; i < N; ++i) {
if (score[i] == maxS) { ++maxCnt; maxIdx.push_back(i); }
if (score[i] == minS) { ++minCnt; minIdx.push_back(i); }
}
// 標準差 σ = sqrt(Σ(xi - μ)² / N)
double var = 0;
for (double s : score) var += (s - avg) * (s - avg);
double stddev = sqrt(var / N);
cout << "最高分:" << maxS << ",人數:" << maxCnt << ",學號:";
for (int idx : maxIdx) cout << idx << ' ';
cout << "\n最低分:" << minS << ",人數:" << minCnt << ",學號:";
for (int idx : minIdx) cout << idx << ' ';
cout << "\n平均分:" << avg << "\n標準差:" << stddev << '\n';
return 0;
}
統計字符串中數字、小寫字母、大寫字母、其他字符個數。
#include
#include // isdigit, islower, isupper
#include
using namespace std;
int main() {
string str;
cout << "請輸入字符串:";
getline(cin, str); // 讀整行含空格
int digit = 0, lower = 0, upper = 0, other = 0;
for (char c : str) {
if (isdigit(c)) ++digit;
else if (islower(c)) ++lower;
else if (isupper(c)) ++upper;
else ++other;
}
cout << "數字:" << digit << "\n小寫:" << lower
<< "\n大寫:" << upper << "\n其他:" << other << '\n';
return 0;
}
使用 <cctype> 標準庫函數比手寫 ASCII 範圍判斷更可移植、可讀性更強。
| 原代碼問題 | 改進方案 |
|---|---|
固定長度數組 int a[10] | vector / array |
手寫 ASCII 比較 c>='0' && c<='9' | isdigit(c) 等標準函數 |
gets(str) 不安全(已移除 C11) | getline(cin, str) 或 fgets |
| 標準差公式圖片 | 代碼直接實現 sqrt(accumulate(...)/N) |
| 學號從 0 開始未說明 | 註釋說明或改為 1-based |
三道基礎練習涵蓋:
max_element accumulate 等<cctype> 標準庫善用 C++ STL 與標準庫,代碼更簡潔、安全、高效,也是現代 C++ 風格的核心體現。