首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 練習題精解:數組去重、成績統計、字符分類

     編輯:關於C++

題目一:數組去重(保留唯一元素)

輸入 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

總結

三道基礎練習涵蓋:

  1. 頻次統計去重 → 哈希表 $O(n)$
  2. 基礎統計量計算 → STL 算法 max_element accumulate 等
  3. 字符分類 → <cctype> 標準庫

善用 C++ STL 與標準庫,代碼更簡潔、安全、高效,也是現代 C++ 風格的核心體現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved