跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
C++算法

C++ 初级实战案例:20 个经典编程练习

包含 20 个 C++ 初级实战案例,涵盖温度转换、闰年判断、阶乘计算、素数筛选、数组排序、字符串处理、斐波那契数列、简易计算器、猜数字游戏、矩阵运算、成绩统计、进制转换、日期计算、汉诺塔递归及字符画图形绘制等内容。每个案例提供完整代码与运行示例,旨在帮助初学者巩固基础语法、掌握常用算法及逻辑结构。

黑客帝国发布于 2026/3/28更新于 2026/9/1075 浏览

案例 1:温度转换器

案例描述

实现摄氏度与华氏度之间的相互转换。

知识点
  • 基本输入输出
  • 数学运算
  • 函数封装
完整代码
#include <iostream>
#include <iomanip>
using namespace std;

// 摄氏度转华氏度
double celsiusToFahrenheit(double celsius) {
    return celsius * 9.0 / 5.0 + 32.0;
}

// 华氏度转摄氏度
double fahrenheitToCelsius(double fahrenheit) {
    return (fahrenheit - 32.0) * 5.0 / 9.0;
}

int main() {
    int choice;
    double temp, result;
    cout << "========== 温度转换器 ==========" << endl;
    cout << "1. 摄氏度转华氏度" << endl;
    cout << "2. 华氏度转摄氏度" << endl;
    cout << "请选择 (1/2): ";
    cin >> choice;
    if (choice == 1) {
        cout << "请输入摄氏度:";
        cin >> temp;
        result = celsiusToFahrenheit(temp);
        cout << fixed << setprecision(2);
        cout << temp << "°C = " << result << "°F" << endl;
    } else if (choice == 2) {
        cout << "请输入华氏度:";
        cin >> temp;
        result = fahrenheitToCelsius(temp);
        cout << fixed << setprecision(2);
        cout << temp << "°F = " << result << "°C" << endl;
    } else {
        cout << "无效选择!" << endl;
    }
    return 0;
}
运行示例
========== 温度转换器 ==========
1. 摄氏度转华氏度
2. 华氏度转摄氏度
请选择 (1/2): 1
请输入摄氏度:25
25.00°C = 77.00°F

案例 2:判断闰年

案例描述

输入一个年份,判断是否为闰年。

知识点
  • 条件判断
  • 逻辑运算符
  • 布尔类型
完整代码
#include <iostream>
using namespace std;

bool isLeapYear(int year) {
    // 闰年条件:能被 4 整除但不能被 100 整除,或能被 400 整除
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int main() {
    int year;
    cout << "请输入年份:";
    cin >> year;
    if (isLeapYear(year)) {
        cout << year << "年是闰年" << endl;
    } else {
        cout << year << "年不是闰年" << endl;
    }
    // 扩展:判断多个年份
    cout << "\n近 10 年的闰年有:" << endl;
    for (int i = year; i < year + 10; i++) {
        if (isLeapYear(i)) {
            cout << i << " ";
        }
    }
    cout << endl;
    return 0;
}
运行示例
请输入年份:2024
2024 年是闰年
近 10 年的闰年有:
2024 2028 2032

案例 3:计算阶乘

案例描述

计算给定数字的阶乘 (n!)。

知识点
  • 循环结构
  • 递归函数
  • 大数处理
完整代码
#include <iostream>
using namespace std;

// 方法 1:循环实现
long long factorialLoop(int n) {
    if (n < 0) return -1; // 错误标识
    if (n == 0 || n == 1) return 1;
    long long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

// 方法 2:递归实现
long long factorialRecursive(int n) {
    if (n < 0) return -1;
    if (n == 0 || n == 1) return 1;
    return n * factorialRecursive(n - 1);
}

int main() {
    int num;
    cout << "请输入一个非负整数:";
    cin >> num;
    if (num < 0) {
        cout << "错误:阶乘不支持负数!" << endl;
        return 1;
    }
    if (num > 20) {
        cout << "警告:数字过大可能溢出,建议输入 0-20 之间的数" << endl;
    }
    long long result1 = factorialLoop(num);
    long long result2 = factorialRecursive(num);
    cout << num << "! = " << result1 << " (循环方法)" << endl;
    cout << num << "! = " << result2 << " (递归方法)" << endl;
    // 显示阶乘表
    cout << "\n阶乘表 (0-10):" << endl;
    for (int i = 0; i <= 10; i++) {
        cout << i << "! = " << factorialLoop(i) << endl;
    }
    return 0;
}
运行示例
请输入一个非负整数:5
5! = 120 (循环方法)
5! = 120 (递归方法)
阶乘表 (0-10):
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

案例 4:素数判断与生成

案例描述

判断一个数是否为素数,并生成指定范围内的所有素数。

知识点
  • 算法优化
  • 循环嵌套
  • 数学逻辑
完整代码
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

// 判断是否为素数(优化版)
bool isPrime(int n) {
    if (n <= 1) return false;
    if (n <= 3) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    // 只需检查到 sqrt(n)
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return false;
        }
    }
    return true;
}

// 生成指定范围内的素数
vector<int> generatePrimes(int start, int end) {
    vector<int> primes;
    for (int i = start; i <= end; i++) {
        if (isPrime(i)) {
            primes.push_back(i);
        }
    }
    return primes;
}

int main() {
    int choice;
    cout << "========== 素数工具 ==========" << endl;
    cout << "1. 判断单个数是否为素数" << endl;
    cout << "2. 生成范围内的素数" << endl;
    cout << "请选择:";
    cin >> choice;
    if (choice == 1) {
        int num;
        cout << "请输入一个数:";
        cin >> num;
        if (isPrime(num)) {
            cout << num << " 是素数" << endl;
        } else {
            cout << num << " 不是素数" << endl;
        }
    } else if (choice == 2) {
        int start, end;
        cout << "请输入范围(起始 结束):";
        cin >> start >> end;
        vector<int> primes = generatePrimes(start, end);
        cout << start << " 到 " << end << " 之间的素数有 " << primes.size() << " 个:" << endl;
        int count = 0;
        for (int prime : primes) {
            cout << prime << " ";
            count++;
            if (count % 10 == 0) cout << endl; // 每行显示 10 个
        }
        cout << endl;
    }
    return 0;
}
运行示例
========== 素数工具 ==========
1. 判断单个数是否为素数
2. 生成范围内的素数
请选择:2
请输入范围(起始 结束): 1 50
1 到 50 之间的素数有 15 个:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

案例 5:数组排序算法

案例描述

实现冒泡排序、选择排序和插入排序三种基本排序算法。

知识点
  • 数组操作
  • 排序算法
  • 函数重载
完整代码
#include <iostream>
#include <algorithm>
using namespace std;

// 打印数组
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// 冒泡排序
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        // 如果没有发生交换,说明已经有序
        if (!swapped) break;
    }
}

// 选择排序
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx]) {
                minIdx = j;
            }
        }
        if (minIdx != i) {
            swap(arr[i], arr[minIdx]);
        }
    }
}

// 插入排序
void insertionSort(int arr[], int n) {
    for (int i = 1; i < n; i++) {
        int key = arr[i];
        int j = i - 1;
        // 将大于 key 的元素向后移动
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "原始数组:";
    printArray(arr, n);
    // 测试冒泡排序
    int arr1[] = {64, 34, 25, 12, 22, 11, 90};
    bubbleSort(arr1, n);
    cout << "冒泡排序:";
    printArray(arr1, n);
    // 测试选择排序
    int arr2[] = {64, 34, 25, 12, 22, 11, 90};
    selectionSort(arr2, n);
    cout << "选择排序:";
    printArray(arr2, n);
    // 测试插入排序
    int arr3[] = {64, 34, 25, 12, 22, 11, 90};
    insertionSort(arr3, n);
    cout << "插入排序:";
    printArray(arr3, n);
    return 0;
}
运行示例
原始数组:64 34 25 12 22 11 90
冒泡排序:11 12 22 25 34 64 90
选择排序:11 12 22 25 34 64 90
插入排序:11 12 22 25 34 64 90

案例 6:字符串反转

案例描述

实现字符串反转的多种方法。

知识点
  • 字符串操作
  • 双指针技巧
  • STL 算法
完整代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// 方法 1:使用双指针
void reverseString1(string& str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        swap(str[left], str[right]);
        left++;
        right--;
    }
}

// 方法 2:使用 STL 的 reverse 函数
void reverseString2(string& str) {
    reverse(str.begin(), str.end());
}

// 方法 3:递归方法
void reverseString3(string& str, int left, int right) {
    if (left >= right) return;
    swap(str[left], str[right]);
    reverseString3(str, left + 1, right - 1);
}

// 反转单词顺序(保持单词内部字符顺序)
string reverseWords(const string& str) {
    string result = "";
    string word = "";
    for (int i = str.length() - 1; i >= 0; i--) {
        if (str[i] == ' ') {
            if (!word.empty()) {
                reverse(word.begin(), word.end());
                result += word + " ";
                word = "";
            }
        } else {
            word += str[i];
        }
    }
    if (!word.empty()) {
        reverse(word.begin(), word.end());
        result += word;
    }
    return result;
}

int main() {
    string str1 = "Hello World";
    string str2 = "Hello World";
    string str3 = "Hello World";
    string str4 = "Hello World from C++";
    cout << "原始字符串:" << str1 << endl;
    reverseString1(str1);
    cout << "方法 1(双指针):" << str1 << endl;
    reverseString2(str2);
    cout << "方法 2(STL):" << str2 << endl;
    reverseString3(str3, 0, str3.length() - 1);
    cout << "方法 3(递归):" << str3 << endl;
    cout << "\n原始句子:" << str4 << endl;
    cout << "反转单词顺序:" << reverseWords(str4) << endl;
    return 0;
}
运行示例
原始字符串:Hello World
方法 1(双指针):dlroW olleH
方法 2(STL):dlroW olleH
方法 3(递归):dlroW olleH
原始句子:Hello World from C++
反转单词顺序:C++ from World Hello

案例 7:查找数组中的最大值和最小值

案例描述

在数组中查找最大值、最小值及其位置。

知识点
  • 数组遍历
  • 变量更新
  • 位置记录
完整代码
#include <iostream>
#include <climits>
using namespace std;

struct MinMax {
    int minValue;
    int maxValue;
    int minIndex;
    int maxIndex;
};

MinMax findMinMax(int arr[], int n) {
    MinMax result;
    result.minValue = INT_MAX;
    result.maxValue = INT_MIN;
    result.minIndex = -1;
    result.maxIndex = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] < result.minValue) {
            result.minValue = arr[i];
            result.minIndex = i;
        }
        if (arr[i] > result.maxValue) {
            result.maxValue = arr[i];
            result.maxIndex = i;
        }
    }
    return result;
}

// 查找第二大的数
int findSecondMax(int arr[], int n) {
    if (n < 2) return -1;
    int max1 = INT_MIN, max2 = INT_MIN;
    for (int i = 0; i < n; i++) {
        if (arr[i] > max1) {
            max2 = max1;
            max1 = arr[i];
        } else if (arr[i] > max2 && arr[i] < max1) {
            max2 = arr[i];
        }
    }
    return (max2 == INT_MIN) ? -1 : max2;
}

int main() {
    int arr[] = {45, 23, 67, 12, 89, 34, 78, 56};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "数组元素:";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    MinMax result = findMinMax(arr, n);
    cout << "\n最小值:" << result.minValue << " (位置:" << result.minIndex << ")" << endl;
    cout << "最大值:" << result.maxValue << " (位置:" << result.maxIndex << ")" << endl;
    int secondMax = findSecondMax(arr, n);
    if (secondMax != -1) {
        cout << "第二大的数:" << secondMax << endl;
    }
    cout << "数值范围:" << result.maxValue - result.minValue << endl;
    return 0;
}
运行示例
数组元素:45 23 67 12 89 34 78 56
最小值:12 (位置:3)
最大值:89 (位置:4)
第二大的数:78
数值范围:77

案例 8:斐波那契数列

案例描述

生成斐波那契数列的前 n 项。

知识点
  • 递归与迭代
  • 动态规划思想
  • 性能优化
完整代码
#include <iostream>
#include <vector>
using namespace std;

// 方法 1:递归(效率低)
long long fibRecursive(int n) {
    if (n <= 1) return n;
    return fibRecursive(n - 1) + fibRecursive(n - 2);
}

// 方法 2:迭代(效率高)
long long fibIterative(int n) {
    if (n <= 1) return n;
    long long a = 0, b = 1;
    for (int i = 2; i <= n; i++) {
        long long temp = a + b;
        a = b;
        b = temp;
    }
    return b;
}

// 方法 3:使用数组存储(动态规划)
vector<long long> fibArray(int n) {
    vector<long long> fib(n + 1);
    fib[0] = 0;
    if (n > 0) fib[1] = 1;
    for (int i = 2; i <= n; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
    }
    return fib;
}

int main() {
    int n;
    cout << "请输入要生成的斐波那契数列项数:";
    cin >> n;
    if (n < 0) {
        cout << "错误:请输入非负整数!" << endl;
        return 1;
    }
    if (n > 50) {
        cout << "警告:数字过大可能溢出,建议输入 0-50 之间的数" << endl;
    }
    // 使用迭代方法生成数列
    cout << "\n斐波那契数列前 " << n + 1 << " 项:" << endl;
    for (int i = 0; i <= n; i++) {
        cout << "F(" << i << ") = " << fibIterative(i) << endl;
    }
    // 使用数组方法一次性生成
    cout << "\n使用数组方法:" << endl;
    vector<long long> fibSeq = fibArray(n);
    for (int i = 0; i <= n; i++) {
        cout << fibSeq[i] << " ";
        if ((i + 1) % 10 == 0) cout << endl;
    }
    cout << endl;
    return 0;
}
运行示例
请输入要生成的斐波那契数列项数:10
斐波那契数列前 11 项:
F(0) = 0
F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
使用数组方法:
0 1 1 2 3 5 8 13 21 34 55

案例 9:回文字符串判断

案例描述

判断一个字符串是否为回文(正读和反读都一样)。

知识点
  • 字符串比较
  • 双指针技巧
  • 字符处理
完整代码
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

// 方法 1:基本判断
bool isPalindrome1(const string& str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        if (str[left] != str[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// 方法 2:忽略大小写和非字母数字字符
bool isPalindrome2(const string& str) {
    int left = 0;
    int right = str.length() - 1;
    while (left < right) {
        // 跳过非字母数字字符
        while (left < right && !isalnum(str[left])) left++;
        while (left < right && !isalnum(str[right])) right--;
        // 比较(忽略大小写)
        if (tolower(str[left]) != tolower(str[right])) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// 找出最长回文子串
string longestPalindrome(const string& str) {
    int n = str.length();
    if (n == 0) return "";
    int maxLen = 1;
    int start = 0;
    // 检查所有子串
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            bool isPalin = true;
            int left = i, right = j;
            while (left < right) {
                if (str[left] != str[right]) {
                    isPalin = false;
                    break;
                }
                left++;
                right--;
            }
            if (isPalin && (j - i + 1) > maxLen) {
                maxLen = j - i + 1;
                start = i;
            }
        }
    }
    return str.substr(start, maxLen);
}

int main() {
    string test1 = "racecar";
    string test2 = "hello";
    string test3 = "A man, a plan, a canal: Panama";
    string test4 = "abcbabcba";
    cout << "\"" << test1 << "\" 是回文:" << (isPalindrome1(test1) ? "是" : "否") << endl;
    cout << "\"" << test2 << "\" 是回文:" << (isPalindrome1(test2) ? "是" : "否") << endl;
    cout << "\"" << test3 << "\" 是回文(忽略符号和大小写):" << (isPalindrome2(test3) ? "是" : "否") << endl;
    cout << "\n\"" << test4 << "\" 的最长回文子串:\"" << longestPalindrome(test4) << "\"" << endl;
    // 交互式测试
    cout << "\n请输入一个字符串:";
    string userInput;
    getline(cin, userInput);
    cout << "基本判断:" << (isPalindrome1(userInput) ? "是回文" : "不是回文") << endl;
    cout << "高级判断:" << (isPalindrome2(userInput) ? "是回文" : "不是回文") << endl;
    return 0;
}
运行示例
"racecar" 是回文:是
"hello" 是回文:否
"A man, a plan, a canal: Panama" 是回文(忽略符号和大小写):是
"abcbabcba" 的最长回文子串:"abcbabcba"
请输入一个字符串:level
基本判断:是回文
高级判断:是回文

案例 10:简易计算器

案例描述

实现一个支持加减乘除和括号的简易计算器。

知识点
  • 表达式解析
  • 运算符优先级
  • 栈的应用
完整代码
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
using namespace std;

// 基础四则运算计算器
class SimpleCalculator {
private:
    // 判断运算符优先级
    int precedence(char op) {
        if (op == '+' || op == '-') return 1;
        if (op == '*' || op == '/') return 2;
        return 0;
    }

    // 执行运算
    double applyOp(double a, double b, char op) {
        switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/':
            if (b == 0) throw runtime_error("除数不能为 0");
            return a / b;
        }
        return 0;
    }

public:
    // 计算表达式
    double evaluate(string expression) {
        stack<double> values; // 存储数字
        stack<char> operators; // 存储运算符
        for (int i = 0; i < expression.length(); i++) {
            // 跳过空格
            if (isspace(expression[i])) continue;
            // 如果是数字
            if (isdigit(expression[i]) || expression[i] == '.') {
                double val = 0;
                bool isDecimal = false;
                double decimalPlace = 0.1;
                while (i < expression.length() && (isdigit(expression[i]) || expression[i] == '.')) {
                    if (expression[i] == '.') {
                        isDecimal = true;
                    } else if (!isDecimal) {
                        val = val * 10 + (expression[i] - '0');
                    } else {
                        val += (expression[i] - '0') * decimalPlace;
                        decimalPlace *= 0.1;
                    }
                    i++;
                }
                i--;
                values.push(val);
            }
            // 如果是左括号
            else if (expression[i] == '(') {
                operators.push(expression[i]);
            }
            // 如果是右括号
            else if (expression[i] == ')') {
                while (!operators.empty() && operators.top() != '(') {
                    double val2 = values.top(); values.pop();
                    double val1 = values.top(); values.pop();
                    char op = operators.top(); operators.pop();
                    values.push(applyOp(val1, val2, op));
                }
                if (!operators.empty()) operators.pop(); // 移除'('
            }
            // 如果是运算符
            else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
                while (!operators.empty() && precedence(operators.top()) >= precedence(expression[i])) {
                    double val2 = values.top(); values.pop();
                    double val1 = values.top(); values.pop();
                    char op = operators.top(); operators.pop();
                    values.push(applyOp(val1, val2, op));
                }
                operators.push(expression[i]);
            }
        }
        // 处理剩余的运算
        while (!operators.empty()) {
            double val2 = values.top(); values.pop();
            double val1 = values.top(); values.pop();
            char op = operators.top(); operators.pop();
            values.push(applyOp(val1, val2, op));
        }
        return values.top();
    }
};

int main() {
    SimpleCalculator calc;
    string expression;
    cout << "========== 简易计算器 ==========" << endl;
    cout << "支持 +、-、*、/、() 运算" << endl;
    cout << "输入 'quit' 退出" << endl;
    cout << "===============================" << endl;
    while (true) {
        cout << "\n请输入表达式:";
        getline(cin, expression);
        if (expression == "quit" || expression == "exit") {
            cout << "再见!" << endl;
            break;
        }
        try {
            double result = calc.evaluate(expression);
            cout << "结果 = " << result << endl;
        } catch (const exception& e) {
            cout << "错误:" << e.what() << endl;
        }
    }
    return 0;
}
运行示例
========== 简易计算器 ==========
支持 +、-、*、/、() 运算
输入 'quit' 退出
===============================
请输入表达式:2 + 3 * 4
结果 = 14
请输入表达式:(2 + 3) * 4
结果 = 20
请输入表达式:10 / 2 + 3
结果 = 8
请输入表达式:quit
再见!

案例 11:猜数字游戏

案例描述

实现一个经典的猜数字游戏,系统随机生成一个数字,玩家猜测并获得提示。

知识点
  • 随机数生成
  • 循环控制
  • 用户交互
完整代码
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

class GuessGame {
private:
    int targetNumber;
    int attempts;
    int maxAttempts;
    int minRange;
    int maxRange;

public:
    GuessGame(int min = 1, int max = 100, int maxTries = 10) : minRange(min), maxRange(max), maxAttempts(maxTries), attempts(0) {
        srand(time(0));
        targetNumber = rand() % (maxRange - minRange + 1) + minRange;
    }

    void play() {
        cout << "\n========== 猜数字游戏 ==========" << endl;
        cout << "我想了一个 " << minRange << " 到 " << maxRange << " 之间的数字" << endl;
        cout << "你有 " << maxAttempts << " 次机会来猜" << endl;
        cout << "===============================" << endl;
        while (attempts < maxAttempts) {
            cout << "\n第 " << (attempts + 1) << " 次猜测,请输入:";
            int guess;
            cin >> guess;
            if (guess < minRange || guess > maxRange) {
                cout << "请输入 " << minRange << " 到 " << maxRange << " 之间的数字!" << endl;
                continue;
            }
            attempts++;
            if (guess == targetNumber) {
                cout << "恭喜你!猜对了!" << endl;
                cout << "你用了 " << attempts << " 次猜中了数字 " << targetNumber << endl;
                return;
            } else if (guess < targetNumber) {
                cout << "太小了!";
                if (targetNumber - guess > 10) {
                    cout << "(还差得远呢)";
                } else {
                    cout << "(快接近了)";
                }
                cout << endl;
            } else {
                cout << "太大了!";
                if (guess - targetNumber > 10) {
                    cout << "(还差得远呢)";
                } else {
                    cout << "(快接近了)";
                }
                cout << endl;
            }
            cout << "剩余机会:" << (maxAttempts - attempts) << endl;
        }
        cout << "\n游戏结束!正确答案是:" << targetNumber << endl;
    }
};

int main() {
    char playAgain;
    do {
        int difficulty;
        cout << "选择难度:1.简单 (1-50,15 次) 2.中等 (1-100,10 次) 3.困难 (1-200,8 次): ";
        cin >> difficulty;
        GuessGame* game;
        switch (difficulty) {
        case 1: game = new GuessGame(1, 50, 15); break;
        case 3: game = new GuessGame(1, 200, 8); break;
        default: game = new GuessGame(1, 100, 10); break;
        }
        game->play();
        delete game;
        cout << "\n再玩一次?(y/n): ";
        cin >> playAgain;
    } while (playAgain == 'y' || playAgain == 'Y');
    cout << "谢谢游玩!" << endl;
    return 0;
}
运行示例
选择难度:1.简单 (1-50,15 次) 2.中等 (1-100,10 次) 3.困难 (1-200,8 次): 2
========== 猜数字游戏 ==========
我想了一个 1 到 100 之间的数字
你有 10 次机会来猜
===============================
第 1 次猜测,请输入:50
太小了!(还差得远呢)
剩余机会:9
第 2 次猜测,请输入:75
太大了!(快接近了)
剩余机会:8
第 3 次猜测,请输入:68
恭喜你!猜对了!
你用了 3 次猜中了数字 68
再玩一次?(y/n): n
谢谢游玩!

案例 12:二维数组矩阵操作

案例描述

实现矩阵的基本操作:转置、加法、乘法。

知识点
  • 二维数组
  • 矩阵运算
  • 函数传递二维数组
完整代码
#include <iostream>
#include <iomanip>
using namespace std;

const int MAX_SIZE = 10;

// 打印矩阵
void printMatrix(int mat[][MAX_SIZE], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << setw(4) << mat[i][j] << " ";
        }
        cout << endl;
    }
}

// 矩阵转置
void transpose(int mat[][MAX_SIZE], int result[][MAX_SIZE], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[j][i] = mat[i][j];
        }
    }
}

// 矩阵加法
bool addMatrix(int mat1[][MAX_SIZE], int mat2[][MAX_SIZE], int result[][MAX_SIZE], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = mat1[i][j] + mat2[i][j];
        }
    }
    return true;
}

// 矩阵乘法
bool multiplyMatrix(int mat1[][MAX_SIZE], int mat2[][MAX_SIZE], int result[][MAX_SIZE], int r1, int c1, int r2, int c2) {
    if (c1 != r2) {
        return false; // 矩阵不能相乘
    }
    // 初始化结果矩阵
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            result[i][j] = 0;
        }
    }
    // 计算乘积
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            for (int k = 0; k < c1; k++) {
                result[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
    return true;
}

int main() {
    int mat1[MAX_SIZE][MAX_SIZE] = {{1, 2, 3}, {4, 5, 6}};
    int mat2[MAX_SIZE][MAX_SIZE] = {{7, 8, 9}, {10, 11, 12}};
    int mat3[MAX_SIZE][MAX_SIZE] = {{1, 2}, {3, 4}, {5, 6}};
    int result[MAX_SIZE][MAX_SIZE];
    cout << "矩阵 A (2x3):" << endl;
    printMatrix(mat1, 2, 3);
    cout << "\n矩阵 B (2x3):" << endl;
    printMatrix(mat2, 2, 3);
    cout << "\n矩阵 C (3x2):" << endl;
    printMatrix(mat3, 3, 2);
    // 转置
    cout << "\n矩阵 A 的转置:" << endl;
    transpose(mat1, result, 2, 3);
    printMatrix(result, 3, 2);
    // 加法
    cout << "\n矩阵 A + 矩阵 B:" << endl;
    addMatrix(mat1, mat2, result, 2, 3);
    printMatrix(result, 2, 3);
    // 乘法
    cout << "\n矩阵 A × 矩阵 C:" << endl;
    if (multiplyMatrix(mat1, mat3, result, 2, 3, 3, 2)) {
        printMatrix(result, 2, 2);
    } else {
        cout << "矩阵维度不匹配,无法相乘!" << endl;
    }
    return 0;
}
运行示例
矩阵 A (2x3):
   1   2   3
   4   5   6
矩阵 B (2x3):
   7   8   9
  10  11  12
矩阵 C (3x2):
   1   2
   3   4
   5   6
矩阵 A 的转置:
   1   4
   2   5
   3   6
矩阵 A + 矩阵 B:
   8  10  12
  14  16  18
矩阵 A × 矩阵 C:
  22  28
  49  64

案例 13:成绩统计系统

案例描述

统计一组学生成绩的平均分、最高分、最低分、及格率等。

知识点
  • 数组统计
  • 数据分析
  • 格式化输出
完整代码
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;

struct ScoreStats {
    double average;
    double highest;
    double lowest;
    double passRate;
    double excellentRate;
    int passCount;
    int excellentCount;
};

ScoreStats analyzeScores(double scores[], int n) {
    ScoreStats stats;
    double sum = 0;
    stats.highest = scores[0];
    stats.lowest = scores[0];
    stats.passCount = 0;
    stats.excellentCount = 0;
    for (int i = 0; i < n; i++) {
        sum += scores[i];
        if (scores[i] > stats.highest) stats.highest = scores[i];
        if (scores[i] < stats.lowest) stats.lowest = scores[i];
        if (scores[i] >= 60) stats.passCount++;
        if (scores[i] >= 90) stats.excellentCount++;
    }
    stats.average = sum / n;
    stats.passRate = (stats.passCount * 100.0) / n;
    stats.excellentRate = (stats.excellentCount * 100.0) / n;
    return stats;
}

void printGradeDistribution(double scores[], int n) {
    int distribution[5] = {0}; // 不及格、及格、中等、良好、优秀
    for (int i = 0; i < n; i++) {
        if (scores[i] < 60) distribution[0]++;
        else if (scores[i] < 70) distribution[1]++;
        else if (scores[i] < 80) distribution[2]++;
        else if (scores[i] < 90) distribution[3]++;
        else distribution[4]++;
    }
    cout << "\n成绩分布:" << endl;
    cout << "不及格 (<60): " << distribution[0] << " 人 (" << fixed << setprecision(1) << (distribution[0] * 100.0 / n) << "% )" << endl;
    cout << "及格 (60-69): " << distribution[1] << " 人 (" << (distribution[1] * 100.0 / n) << "% )" << endl;
    cout << "中等 (70-79): " << distribution[2] << " 人 (" << (distribution[2] * 100.0 / n) << "% )" << endl;
    cout << "良好 (80-89): " << distribution[3] << " 人 (" << (distribution[3] * 100.0 / n) << "% )" << endl;
    cout << "优秀 (90-100): " << distribution[4] << " 人 (" << (distribution[4] * 100.0 / n) << "% )" << endl;
}

int main() {
    const int MAX_STUDENTS = 100;
    double scores[MAX_STUDENTS];
    int n;
    cout << "请输入学生人数:";
    cin >> n;
    if (n <= 0 || n > MAX_STUDENTS) {
        cout << "学生人数无效!" << endl;
        return 1;
    }
    cout << "请输入 " << n << " 个学生的成绩:" << endl;
    for (int i = 0; i < n; i++) {
        cout << "学生" << (i + 1) << ": ";
        cin >> scores[i];
        if (scores[i] < 0 || scores[i] > 100) {
            cout << "成绩无效,请重新输入!" << endl;
            i--;
        }
    }
    ScoreStats stats = analyzeScores(scores, n);
    cout << "\n========== 成绩统计结果 ==========" << endl;
    cout << fixed << setprecision(2);
    cout << "平均分:" << stats.average << endl;
    cout << "最高分:" << stats.highest << endl;
    cout << "最低分:" << stats.lowest << endl;
    cout << "及格人数:" << stats.passCount << " 人" << endl;
    cout << "及格率:" << stats.passRate << "%" << endl;
    cout << "优秀人数:" << stats.excellentCount << " 人" << endl;
    cout << "优秀率:" << stats.excellentRate << "%" << endl;
    printGradeDistribution(scores, n);
    // 排序后显示
    sort(scores, scores + n);
    cout << "\n成绩排序(从低到高):" << endl;
    for (int i = 0; i < n; i++) {
        cout << scores[i] << " ";
        if ((i + 1) % 10 == 0) cout << endl;
    }
    cout << endl;
    return 0;
}
运行示例
请输入学生人数:10
请输入 10 个学生的成绩:
学生 1: 85
学生 2: 92
学生 3: 78
学生 4: 65
学生 5: 88
学生 6: 76
学生 7: 95
学生 8: 58
学生 9: 82
学生 10: 90
========== 成绩统计结果 ==========
平均分:80.90
最高分:95.00
最低分:58.00
及格人数:9 人
及格率:90.00%
优秀人数:3 人
优秀率:30.00%
成绩分布:
不及格 (<60): 1 人 (10.0%)
及格 (60-69): 1 人 (10.0%)
中等 (70-79): 2 人 (20.0%)
良好 (80-89): 3 人 (30.0%)
优秀 (90-100): 3 人 (30.0%)
成绩排序(从低到高):
58.00 65.00 76.00 78.00 82.00 85.00 88.00 90.00 92.00 95.00

案例 14:字符串统计分析

案例描述

统计字符串中字母、数字、空格和其他字符的数量。

知识点
  • 字符分类函数
  • 字符串遍历
  • 统计分析
完整代码
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

struct CharStats {
    int letters;
    int digits;
    int spaces;
    int uppercase;
    int lowercase;
    int punctuation;
    int others;
    int total;
};

CharStats analyzeString(const string& str) {
    CharStats stats = {0, 0, 0, 0, 0, 0, 0, 0};
    for (char ch : str) {
        stats.total++;
        if (isalpha(ch)) {
            stats.letters++;
            if (isupper(ch)) stats.uppercase++;
            else stats.lowercase++;
        } else if (isdigit(ch)) {
            stats.digits++;
        } else if (isspace(ch)) {
            stats.spaces++;
        } else if (ispunct(ch)) {
            stats.punctuation++;
        } else {
            stats.others++;
        }
    }
    return stats;
}

// 统计单词数量
int countWords(const string& str) {
    int count = 0;
    bool inWord = false;
    for (char ch : str) {
        if (isspace(ch)) {
            inWord = false;
        } else if (!inWord) {
            inWord = true;
            count++;
        }
    }
    return count;
}

// 查找最长单词
string findLongestWord(const string& str) {
    string longestWord = "";
    string currentWord = "";
    for (char ch : str) {
        if (isalnum(ch)) {
            currentWord += ch;
        } else {
            if (currentWord.length() > longestWord.length()) {
                longestWord = currentWord;
            }
            currentWord = "";
        }
    }
    // 检查最后一个单词
    if (currentWord.length() > longestWord.length()) {
        longestWord = currentWord;
    }
    return longestWord;
}

int main() {
    string text;
    cout << "请输入一段文本:" << endl;
    getline(cin, text);
    CharStats stats = analyzeString(text);
    cout << "\n========== 字符统计分析 ==========" << endl;
    cout << "总字符数:" << stats.total << endl;
    cout << "字母数:" << stats.letters << " (大写:" << stats.uppercase << ", 小写:" << stats.lowercase << ")" << endl;
    cout << "数字数:" << stats.digits << endl;
    cout << "空格数:" << stats.spaces << endl;
    cout << "标点符号:" << stats.punctuation << endl;
    cout << "其他字符:" << stats.others << endl;
    int wordCount = countWords(text);
    string longestWord = findLongestWord(text);
    cout << "\n单词数:" << wordCount << endl;
    cout << "最长单词:\"" << longestWord << "\" (长度:" << longestWord.length() << ")" << endl;
    // 字符频率统计
    cout << "\n字母频率统计:" << endl;
    int freq[26] = {0};
    for (char ch : text) {
        if (isalpha(ch)) {
            freq[tolower(ch) - 'a']++;
        }
    }
    for (int i = 0; i < 26; i++) {
        if (freq[i] > 0) {
            cout << char('a' + i) << ": " << freq[i] << " ";
            if ((i + 1) % 5 == 0) cout << endl;
        }
    }
    cout << endl;
    return 0;
}
运行示例
请输入一段文本:
Hello World! This is a C++ programming example. Count123
========== 字符统计分析 ==========
总字符数:56
字母数:43 (大写:5, 小写:38)
数字数:3
空格数:7
标点符号:2
其他字符:1
单词数:8
最长单词:"programming" (长度:11)
字母频率统计:
a: 3 c: 2 d: 1 e: 4 g: 2 h: 2 i: 3 l: 3 m: 3 n: 2 o: 4 p: 2 r: 3 s: 2 t: 2 u: 1 w: 1 x: 1

案例 15:简易银行账户系统

案例描述

实现一个简单的银行账户管理系统,支持存款、取款、查询余额等操作。

知识点
  • 结构体应用
  • 函数封装
  • 数据验证
完整代码
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

struct BankAccount {
    string accountNumber;
    string ownerName;
    double balance;
    string password;
};

class SimpleBankSystem {
private:
    BankAccount accounts[100];
    int accountCount;

    int findAccount(const string& accountNumber) {
        for (int i = 0; i < accountCount; i++) {
            if (accounts[i].accountNumber == accountNumber) {
                return i;
            }
        }
        return -1;
    }

public:
    SimpleBankSystem() : accountCount(0) {}

    void createAccount() {
        if (accountCount >= 100) {
            cout << "系统已满,无法创建新账户!" << endl;
            return;
        }
        BankAccount newAccount;
        cout << "\n创建新账户" << endl;
        cout << "账号:";
        cin >> newAccount.accountNumber;
        if (findAccount(newAccount.accountNumber) != -1) {
            cout << "账号已存在!" << endl;
            return;
        }
        cout << "户名:";
        cin.ignore();
        getline(cin, newAccount.ownerName);
        cout << "初始存款:";
        cin >> newAccount.balance;
        if (newAccount.balance < 0) {
            cout << "初始存款不能为负!" << endl;
            return;
        }
        cout << "设置密码:";
        cin >> newAccount.password;
        accounts[accountCount++] = newAccount;
        cout << "账户创建成功!" << endl;
    }

    void deposit() {
        string accountNumber;
        double amount;
        cout << "\n存款" << endl;
        cout << "账号:";
        cin >> accountNumber;
        int index = findAccount(accountNumber);
        if (index == -1) {
            cout << "账号不存在!" << endl;
            return;
        }
        cout << "存款金额:";
        cin >> amount;
        if (amount <= 0) {
            cout << "存款金额必须大于 0!" << endl;
            return;
        }
        accounts[index].balance += amount;
        cout << "存款成功!当前余额:" << fixed << setprecision(2) << accounts[index].balance << " 元" << endl;
    }

    void withdraw() {
        string accountNumber, password;
        double amount;
        cout << "\n取款" << endl;
        cout << "账号:";
        cin >> accountNumber;
        int index = findAccount(accountNumber);
        if (index == -1) {
            cout << "账号不存在!" << endl;
            return;
        }
        cout << "密码:";
        cin >> password;
        if (password != accounts[index].password) {
            cout << "密码错误!" << endl;
            return;
        }
        cout << "取款金额:";
        cin >> amount;
        if (amount <= 0) {
            cout << "取款金额必须大于 0!" << endl;
            return;
        }
        if (amount > accounts[index].balance) {
            cout << "余额不足!当前余额:" << fixed << setprecision(2) << accounts[index].balance << " 元" << endl;
            return;
        }
        accounts[index].balance -= amount;
        cout << "取款成功!当前余额:" << fixed << setprecision(2) << accounts[index].balance << " 元" << endl;
    }

    void checkBalance() {
        string accountNumber, password;
        cout << "\n查询余额" << endl;
        cout << "账号:";
        cin >> accountNumber;
        int index = findAccount(accountNumber);
        if (index == -1) {
            cout << "账号不存在!" << endl;
            return;
        }
        cout << "密码:";
        cin >> password;
        if (password != accounts[index].password) {
            cout << "密码错误!" << endl;
            return;
        }
        cout << "\n账户信息" << endl;
        cout << "账号:" << accounts[index].accountNumber << endl;
        cout << "户名:" << accounts[index].ownerName << endl;
        cout << "余额:" << fixed << setprecision(2) << accounts[index].balance << " 元" << endl;
    }

    void showMenu() {
        cout << "\n========== 简易银行系统 ==========" << endl;
        cout << "1. 创建账户" << endl;
        cout << "2. 存款" << endl;
        cout << "3. 取款" << endl;
        cout << "4. 查询余额" << endl;
        cout << "5. 退出" << endl;
        cout << "=================================" << endl;
        cout << "请选择:";
    }
};

int main() {
    SimpleBankSystem bank;
    int choice;
    while (true) {
        bank.showMenu();
        cin >> choice;
        switch (choice) {
        case 1: bank.createAccount(); break;
        case 2: bank.deposit(); break;
        case 3: bank.withdraw(); break;
        case 4: bank.checkBalance(); break;
        case 5: cout << "感谢使用!再见!" << endl; return 0;
        default: cout << "无效选择!" << endl;
        }
    }
    return 0;
}
运行示例
========== 简易银行系统 ==========
1. 创建账户
2. 存款
3. 取款
4. 查询余额
5. 退出
=================================
请选择:1
创建新账户
账号:1001
户名:张三
初始存款:1000
设置密码:123456
账户创建成功!
========== 简易银行系统 ==========
请选择:2
存款
账号:1001
存款金额:500
存款成功!当前余额:1500.00 元
========== 简易银行系统 ==========
请选择:3
取款
账号:1001
密码:123456
取款金额:200
取款成功!当前余额:1300.00 元

案例 16:进制转换器

案例描述

实现二进制、八进制、十进制、十六进制之间的相互转换。

知识点
  • 进制转换算法
  • 字符串处理
  • 数学运算
完整代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// 十进制转其他进制
string decimalToBase(int decimal, int base) {
    if (decimal == 0) return "0";
    string result = "";
    const char digits[] = "0123456789ABCDEF";
    bool isNegative = decimal < 0;
    decimal = abs(decimal);
    while (decimal > 0) {
        result += digits[decimal % base];
        decimal /= base;
    }
    if (isNegative) result += '-';
    reverse(result.begin(), result.end());
    return result;
}

// 其他进制转十进制
int baseToDecimal(const string& number, int base) {
    int result = 0;
    int power = 1;
    bool isNegative = (number[0] == '-');
    int startPos = isNegative ? 1 : 0;
    for (int i = number.length() - 1; i >= startPos; i--) {
        char digit = number[i];
        int value;
        if (digit >= '0' && digit <= '9') {
            value = digit - '0';
        } else if (digit >= 'A' && digit <= 'F') {
            value = digit - 'A' + 10;
        } else if (digit >= 'a' && digit <= 'f') {
            value = digit - 'a' + 10;
        } else {
            return -1; // 无效字符
        }
        if (value >= base) {
            return -1; // 数字超出进制范围
        }
        result += value * power;
        power *= base;
    }
    return isNegative ? -result : result;
}

void showConversions(int decimal) {
    cout << "\n========== 进制转换结果 ==========" << endl;
    cout << "十进制:" << decimal << endl;
    cout << "二进制:" << decimalToBase(decimal, 2) << endl;
    cout << "八进制:" << decimalToBase(decimal, 8) << endl;
    cout << "十六进制:" << decimalToBase(decimal, 16) << endl;
    cout << "================================" << endl;
}

int main() {
    int choice;
    while (true) {
        cout << "\n========== 进制转换器 ==========" << endl;
        cout << "1. 十进制转其他进制" << endl;
        cout << "2. 二进制转十进制" << endl;
        cout << "3. 八进制转十进制" << endl;
        cout << "4. 十六进制转十进制" << endl;
        cout << "5. 退出" << endl;
        cout << "===============================" << endl;
        cout << "请选择:";
        cin >> choice;
        if (choice == 5) {
            cout << "再见!" << endl;
            break;
        }
        switch (choice) {
        case 1: {
            int decimal;
            cout << "请输入十进制数:";
            cin >> decimal;
            showConversions(decimal);
            break;
        }
        case 2: {
            string binary;
            cout << "请输入二进制数:";
            cin >> binary;
            int decimal = baseToDecimal(binary, 2);
            if (decimal == -1) {
                cout << "无效的二进制数!" << endl;
            } else {
                showConversions(decimal);
            }
            break;
        }
        case 3: {
            string octal;
            cout << "请输入八进制数:";
            cin >> octal;
            int decimal = baseToDecimal(octal, 8);
            if (decimal == -1) {
                cout << "无效的八进制数!" << endl;
            } else {
                showConversions(decimal);
            }
            break;
        }
        case 4: {
            string hex;
            cout << "请输入十六进制数:";
            cin >> hex;
            int decimal = baseToDecimal(hex, 16);
            if (decimal == -1) {
                cout << "无效的十六进制数!" << endl;
            } else {
                showConversions(decimal);
            }
            break;
        }
        default: cout << "无效选择!" << endl;
        }
    }
    return 0;
}
运行示例
========== 进制转换器 ==========
1. 十进制转其他进制
2. 二进制转十进制
3. 八进制转十进制
4. 十六进制转十进制
5. 退出
===============================
请选择:1
请输入十进制数:255
========== 进制转换结果 ==========
十进制:255
二进制:11111111
八进制:377
十六进制:FF
================================

案例 17:日期计算器

案例描述

计算两个日期之间的天数差,判断是否为有效日期。

知识点
  • 日期算法
  • 闰年判断
  • 逻辑运算
完整代码
#include <iostream>
using namespace std;

struct Date {
    int year;
    int month;
    int day;
};

// 判断是否为闰年
bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 获取某月的天数
int getDaysInMonth(int year, int month) {
    int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month == 2 && isLeapYear(year)) {
        return 29;
    }
    return days[month];
}

// 判断日期是否有效
bool isValidDate(const Date& date) {
    if (date.year < 1 || date.month < 1 || date.month > 12 || date.day < 1) {
        return false;
    }
    int maxDay = getDaysInMonth(date.year, date.month);
    return date.day <= maxDay;
}

// 计算从公元 1 年 1 月 1 日到指定日期的天数
int dateToDays(const Date& date) {
    int days = 0;
    // 计算年份的天数
    for (int y = 1; y < date.year; y++) {
        days += isLeapYear(y) ? 366 : 365;
    }
    // 计算月份的天数
    for (int m = 1; m < date.month; m++) {
        days += getDaysInMonth(date.year, m);
    }
    // 加上日期
    days += date.day;
    return days;
}

// 计算两个日期之间的天数差
int daysBetween(const Date& date1, const Date& date2) {
    return abs(dateToDays(date1) - dateToDays(date2));
}

// 获取星期几(0=周日,1=周一,..., 6=周六)
int getDayOfWeek(const Date& date) {
    // 使用蔡勒公式
    int y = date.year;
    int m = date.month;
    int d = date.day;
    if (m < 3) {
        m += 12;
        y--;
    }
    int c = y / 100;
    y = y % 100;
    int w = (y + y / 4 + c / 4 - 2 * c + (26 * (m + 1)) / 10 + d - 1) % 7;
    return (w + 7) % 7;
}

const char* getWeekDayName(int dayOfWeek) {
    const char* names[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    return names[dayOfWeek];
}

int main() {
    Date date1, date2;
    cout << "========== 日期计算器 ==========" << endl;
    cout << "请输入第一个日期(年 月 日):";
    cin >> date1.year >> date1.month >> date1.day;
    if (!isValidDate(date1)) {
        cout << "日期 1 无效!" << endl;
        return 1;
    }
    cout << "请输入第二个日期(年 月 日):";
    cin >> date2.year >> date2.month >> date2.day;
    if (!isValidDate(date2)) {
        cout << "日期 2 无效!" << endl;
        return 1;
    }
    int days = daysBetween(date1, date2);
    cout << "\n========== 计算结果 ==========" << endl;
    cout << "日期 1: " << date1.year << "年" << date1.month << "月" << date1.day << "日 " << getWeekDayName(getDayOfWeek(date1)) << endl;
    cout << "日期 2: " << date2.year << "年" << date2.month << "月" << date2.day << "日 " << getWeekDayName(getDayOfWeek(date2)) << endl;
    cout << "相差天数:" << days << " 天" << endl;
    cout << "相差周数:" << days / 7 << " 周 " << days % 7 << " 天" << endl;
    return 0;
}
运行示例
========== 日期计算器 ==========
请输入第一个日期(年 月 日): 2024 1 1
请输入第二个日期(年 月 日): 2024 12 31
========== 计算结果 ==========
日期 1: 2024 年 1 月 1 日 周一
日期 2: 2024 年 12 月 31 日 周二
相差天数:365 天
相差周数:52 周 1 天

案例 18:汉诺塔问题

案例描述

经典的汉诺塔递归问题,将 n 个盘子从 A 柱移动到 C 柱。

知识点
  • 递归思想
  • 问题分解
  • 算法设计
完整代码
#include <iostream>
using namespace std;

int moveCount = 0;

// 汉诺塔递归解法
void hanoi(int n, char from, char to, char aux) {
    if (n == 1) {
        moveCount++;
        cout << "第 " << moveCount << " 步:将盘子 " << n << " 从 " << from << " 移动到 " << to << endl;
        return;
    }
    // 将 n-1 个盘子从 from 移动到 aux(借助 to)
    hanoi(n - 1, from, aux, to);
    // 将第 n 个盘子从 from 移动到 to
    moveCount++;
    cout << "第 " << moveCount << " 步:将盘子 " << n << " 从 " << from << " 移动到 " << to << endl;
    // 将 n-1 个盘子从 aux 移动到 to(借助 from)
    hanoi(n - 1, aux, to, from);
}

// 计算最少步数
int minSteps(int n) {
    return (1 << n) - 1; // 2^n - 1
}

int main() {
    int n;
    cout << "========== 汉诺塔问题 ==========" << endl;
    cout << "请输入盘子数量:";
    cin >> n;
    if (n <= 0) {
        cout << "盘子数量必须大于 0!" << endl;
        return 1;
    }
    if (n > 10) {
        cout << "盘子数量过多,步骤会很多(2^" << n << "-1 = " << minSteps(n) << " 步)" << endl;
        cout << "建议输入 10 以内的数字" << endl;
        cout << "是否继续?(y/n): ";
        char choice;
        cin >> choice;
        if (choice != 'y' && choice != 'Y') {
            return 0;
        }
    }
    cout << "\n理论最少步数:" << minSteps(n) << " 步" << endl;
    cout << "\n开始移动..." << endl;
    cout << "A 柱 (起始) -> C 柱 (目标),B 柱 (辅助)" << endl;
    cout << "==============================" << endl;
    moveCount = 0;
    hanoi(n, 'A', 'C', 'B');
    cout << "\n==============================" << endl;
    cout << "完成!总共移动了 " << moveCount << " 次" << endl;
    return 0;
}
运行示例
========== 汉诺塔问题 ==========
请输入盘子数量:3
理论最少步数:7 步
开始移动...
A 柱 (起始) -> C 柱 (目标),B 柱 (辅助)
===============================
第 1 步:将盘子 1 从 A 移动到 C
第 2 步:将盘子 2 从 A 移动到 B
第 3 步:将盘子 1 从 C 移动到 B
第 4 步:将盘子 3 从 A 移动到 C
第 5 步:将盘子 1 从 B 移动到 A
第 6 步:将盘子 2 从 B 移动到 C
第 7 步:将盘子 1 从 A 移动到 C
===============================
完成!总共移动了 7 次

案例 19:杨辉三角

案例描述

打印指定行数的杨辉三角(帕斯卡三角)。

知识点
  • 二维数组
  • 数学规律
  • 格式化输出
完整代码
#include <iostream>
#include <iomanip>
using namespace std;

void printPascalTriangle(int n) {
    int triangle[100][100] = {0};
    // 生成杨辉三角
    for (int i = 0; i < n; i++) {
        triangle[i][0] = 1; // 每行第一个数为 1
        triangle[i][i] = 1; // 对角线上的数为 1
        for (int j = 1; j < i; j++) {
            triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
        }
    }
    // 打印杨辉三角
    cout << "\n========== 杨辉三角 ==========" << endl;
    for (int i = 0; i < n; i++) {
        // 打印前导空格,使三角形居中
        for (int k = 0; k < (n - i - 1) * 2; k++) {
            cout << " ";
        }
        for (int j = 0; j <= i; j++) {
            cout << setw(4) << triangle[i][j];
        }
        cout << endl;
    }
    cout << "=============================" << endl;
}

// 计算组合数 C(n, k) = n! / (k! * (n-k)!)
long long combination(int n, int k) {
    if (k > n - k) k = n - k; // 优化计算
    long long result = 1;
    for (int i = 0; i < k; i++) {
        result *= (n - i);
        result /= (i + 1);
    }
    return result;
}

// 使用组合数公式打印
void printPascalTriangleByFormula(int n) {
    cout << "\n使用组合数公式:" << endl;
    for (int i = 0; i < n; i++) {
        for (int k = 0; k < (n - i - 1) * 2; k++) {
            cout << " ";
        }
        for (int j = 0; j <= i; j++) {
            cout << setw(4) << combination(i, j);
        }
        cout << endl;
    }
}

// 打印特定行
void printRow(int row) {
    cout << "第 " << row + 1 << " 行:";
    for (int i = 0; i <= row; i++) {
        cout << combination(row, i) << " ";
    }
    cout << endl;
}

int main() {
    int n;
    cout << "请输入杨辉三角的行数:";
    cin >> n;
    if (n <= 0 || n > 30) {
        cout << "行数应在 1-30 之间!" << endl;
        return 1;
    }
    printPascalTriangle(n);
    cout << "\n杨辉三角的性质:" << endl;
    cout << "1. 每行首尾都是 1" << endl;
    cout << "2. 每个数等于它上方两个数之和" << endl;
    cout << "3. 第 n 行的数字是组合数 C(n-1, k)" << endl;
    cout << "4. 每行数字之和为 2^(n-1)" << endl;
    // 验证性质 4
    cout << "\n验证:第 " << n << " 行数字之和 = ";
    long long sum = 0;
    for (int i = 0; i < n; i++) {
        sum += combination(n - 1, i);
    }
    cout << sum << " = 2^" << (n - 1) << " = " << (1 << (n - 1)) << endl;
    return 0;
}
运行示例
请输入杨辉三角的行数:7
========== 杨辉三角 ==========
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1
 1 5 10 10 5 1
1 6 15 20 15 6 1
=============================
杨辉三角的性质:
1. 每行首尾都是 1
2. 每个数等于它上方两个数之和
3. 第 n 行的数字是组合数 C(n-1, k)
4. 每行数字之和为 2^(n-1)
验证:第 7 行数字之和 = 64 = 2^6 = 64

案例 20:字符画图形

案例描述

使用字符绘制各种图形(三角形、菱形、心形等)。

知识点
  • 循环嵌套
  • 空格控制
  • 图形规律
完整代码
#include <iostream>
using namespace std;

// 直角三角形
void printRightTriangle(int n) {
    cout << "\n直角三角形:" << endl;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }
}

// 等腰三角形
void printIsoscelesTriangle(int n) {
    cout << "\n等腰三角形:" << endl;
    for (int i = 1; i <= n; i++) {
        // 打印空格
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        // 打印星号
        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }
        cout << endl;
    }
}

// 菱形
void printDiamond(int n) {
    cout << "\n菱形:" << endl;
    // 上半部分
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }
        cout << endl;
    }
    // 下半部分
    for (int i = n - 1; i >= 1; i--) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for (int j = 1; j <= 2 * i - 1; j++) {
            cout << "*";
        }
        cout << endl;
    }
}

// 空心菱形
void printHollowDiamond(int n) {
    cout << "\n空心菱形:" << endl;
    // 上半部分
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for (int j = 1; j <= 2 * i - 1; j++) {
            if (j == 1 || j == 2 * i - 1) {
                cout << "*";
            } else {
                cout << " ";
            }
        }
        cout << endl;
    }
    // 下半部分
    for (int i = n - 1; i >= 1; i--) {
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        for (int j = 1; j <= 2 * i - 1; j++) {
            if (j == 1 || j == 2 * i - 1) {
                cout << "*";
            } else {
                cout << " ";
            }
        }
        cout << endl;
    }
}

// 心形
void printHeart(int n) {
    cout << "\n心形:" << endl;
    // 上半部分
    for (int i = n / 2; i < n; i += 2) {
        // 左边空格
        for (int j = 1; j < n - i; j += 2) {
            cout << " ";
        }
        // 左边的心形
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }
        // 中间空格
        for (int j = 1; j <= n - i; j++) {
            cout << " ";
        }
        // 右边的心形
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }
        cout << endl;
    }
    // 下半部分
    for (int i = n; i >= 1; i--) {
        for (int j = 0; j < n - i; j++) {
            cout << " ";
        }
        for (int j = 1; j <= i * 2 - 1; j++) {
            cout << "*";
        }
        cout << endl;
    }
}

// 矩形
void printRectangle(int rows, int cols) {
    cout << "\n矩形 (" << rows << "x" << cols << "):" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) {
                cout << "* ";
            } else {
                cout << " ";
            }
        }
        cout << endl;
    }
}

int main() {
    int choice, size;
    while (true) {
        cout << "\n========== 字符画图形 ==========" << endl;
        cout << "1. 直角三角形" << endl;
        cout << "2. 等腰三角形" << endl;
        cout << "3. 菱形" << endl;
        cout << "4. 空心菱形" << endl;
        cout << "5. 心形" << endl;
        cout << "6. 矩形" << endl;
        cout << "7. 显示所有图形" << endl;
        cout << "8. 退出" << endl;
        cout << "===============================" << endl;
        cout << "请选择:";
        cin >> choice;
        if (choice == 8) {
            cout << "再见!" << endl;
            break;
        }
        if (choice == 7) {
            size = 5;
            printRightTriangle(size);
            printIsoscelesTriangle(size);
            printDiamond(size);
            printHollowDiamond(size);
            printHeart(6);
            printRectangle(5, 10);
            continue;
        }
        cout << "请输入图形大小:";
        cin >> size;
        if (size <= 0 || size > 20) {
            cout << "大小应在 1-20 之间!" << endl;
            continue;
        }
        switch (choice) {
        case 1: printRightTriangle(size); break;
        case 2: printIsoscelesTriangle(size); break;
        case 3: printDiamond(size); break;
        case 4: printHollowDiamond(size); break;
        case 5: printHeart(size); break;
        case 6: {
            int cols;
            cout << "请输入列数:";
            cin >> cols;
            printRectangle(size, cols);
            break;
        }
        default: cout << "无效选择!" << endl;
        }
    }
    return 0;
}
运行示例
========== 字符画图形 ==========
1. 直角三角形
2. 等腰三角形
3. 菱形
4. 空心菱形
5. 心形
6. 矩形
7. 显示所有图形
8. 退出
===============================
请选择:3
请输入图形大小:5
菱形:
 *
***
*****
*******
*********
*******
*****
***
*

目录

  1. 案例 1:温度转换器
  2. 案例描述
  3. 知识点
  4. 完整代码
  5. 运行示例
  6. 案例 2:判断闰年
  7. 案例描述
  8. 知识点
  9. 完整代码
  10. 运行示例
  11. 案例 3:计算阶乘
  12. 案例描述
  13. 知识点
  14. 完整代码
  15. 运行示例
  16. 案例 4:素数判断与生成
  17. 案例描述
  18. 知识点
  19. 完整代码
  20. 运行示例
  21. 案例 5:数组排序算法
  22. 案例描述
  23. 知识点
  24. 完整代码
  25. 运行示例
  26. 案例 6:字符串反转
  27. 案例描述
  28. 知识点
  29. 完整代码
  30. 运行示例
  31. 案例 7:查找数组中的最大值和最小值
  32. 案例描述
  33. 知识点
  34. 完整代码
  35. 运行示例
  36. 案例 8:斐波那契数列
  37. 案例描述
  38. 知识点
  39. 完整代码
  40. 运行示例
  41. 案例 9:回文字符串判断
  42. 案例描述
  43. 知识点
  44. 完整代码
  45. 运行示例
  46. 案例 10:简易计算器
  47. 案例描述
  48. 知识点
  49. 完整代码
  50. 运行示例
  51. 案例 11:猜数字游戏
  52. 案例描述
  53. 知识点
  54. 完整代码
  55. 运行示例
  56. 案例 12:二维数组矩阵操作
  57. 案例描述
  58. 知识点
  59. 完整代码
  60. 运行示例
  61. 案例 13:成绩统计系统
  62. 案例描述
  63. 知识点
  64. 完整代码
  65. 运行示例
  66. 案例 14:字符串统计分析
  67. 案例描述
  68. 知识点
  69. 完整代码
  70. 运行示例
  71. 案例 15:简易银行账户系统
  72. 案例描述
  73. 知识点
  74. 完整代码
  75. 运行示例
  76. 案例 16:进制转换器
  77. 案例描述
  78. 知识点
  79. 完整代码
  80. 运行示例
  81. 案例 17:日期计算器
  82. 案例描述
  83. 知识点
  84. 完整代码
  85. 运行示例
  86. 案例 18:汉诺塔问题
  87. 案例描述
  88. 知识点
  89. 完整代码
  90. 运行示例
  91. 案例 19:杨辉三角
  92. 案例描述
  93. 知识点
  94. 完整代码
  95. 运行示例
  96. 案例 20:字符画图形
  97. 案例描述
  98. 知识点
  99. 完整代码
  100. 运行示例

更多推荐文章

查看全部
  • 7 款高颜值 Linux 发行版推荐
  • 算法实战:位运算解决整数求和、唯一数与缺失数字
  • 2026 年 3 月 GESP 真题解析:数字替换 (C++)
  • Raphael AI:基于 Flux 模型的免费 AI 图像生成工具解析
  • 多模态大模型解析:InternVL-v1.5 与 Qwen2VL 架构对比
  • Discord 机器人创建与配置流程
  • Selenium Web 自动化测试入门与实战指南
  • Claude Code vs GitHub Copilot CLI 终端开发深度评测
  • OpenClaw 开源 AI 助手安装与使用教程
  • 2024 中国 AI 大模型场景探索与应用趋势深度解析
  • Python 基础语法与面向对象编程入门指南
  • 网络安全职业发展路径与技能规划指南
  • Spatial Joy 2025 全球 AR&AI 开发大赛参赛指南与资源解析
  • Python 入门:30 天零基础学习规划(每日 1 小时)
  • 基于 WebUploader 与 PHP 的飞行日志分片上传可靠性方案
  • 双指针算法实战:快乐数与盛最多水的容器
  • Anaconda 安装与 Python 环境配置详解
  • Python 学习路线与核心知识点详解
  • 华为鸿蒙及安卓手机谷歌验证器安装指南与替代方案
  • AIGC 时代 Kubernetes 企业级云原生运维实战:智能重构与深度实践

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online