蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 20 道经典 C++ 实例核心算法(算术/sizeof/二次方程/阶乘/GCD-LCM/计算器/猴子吃桃)

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-examples.cpp
explore-cpp-examples.cpp166 行
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

bool is_leap(int y) {
    return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}

bool is_vowel(char c) {
    switch (c) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
        case 'A': case 'E': case 'I': case 'O': case 'U':
            return true;
        default:
            return false;
    }
}

double calc(double a, char op, double b) {
    switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return b != 0.0 ? a / b : 0.0;
        default: return 0.0;
    }
}

} // namespace lab

int main() {
    std::vector<lab::Case> cases;

    // Case 1: Basic IO, arithmetic, quotient/remainder, sizeof, swap
    std::ostringstream hello;
    hello << "Hello, World!\n";
    int a = 17, b = 5;
    int sum = a + b, quot = a / b, rem = a % b;
    int x = 3, y = 8;
    std::swap(x, y);
    bool ok1 = (hello.str() == "Hello, World!\n") &&
               (sum == 22 && quot == 3 && rem == 2) &&
               (x == 8 && y == 3) &&
               (sizeof(char) == 1 && sizeof(int) >= 4 &&
                sizeof(float) == 4 && sizeof(double) == 8);
    cases.push_back({
        "basic_io_arithmetic_and_sizes",
        lab::jbool(true),
        lab::jbool(ok1),
        ok1
    });

    // Case 2: Odd/even, vowel/consonant, max of 3, leap year, quadratic equation x^2 - 5x + 6 = 0
    bool even_check = (42 % 2 == 0) && (43 % 2 != 0);
    bool vowel_check = lab::is_vowel('E') && !lab::is_vowel('k');
    int max3 = std::max({14, 29, 21});
    bool leap_check = lab::is_leap(2000) && !lab::is_leap(1900) && lab::is_leap(2024);
    double qa = 1.0, qb = -5.0, qc = 6.0;
    double disc = qb * qb - 4.0 * qa * qc;
    double r1 = (-qb - std::sqrt(disc)) / (2.0 * qa);
    double r2 = (-qb + std::sqrt(disc)) / (2.0 * qa);
    bool ok2 = even_check && vowel_check && (max3 == 29) && leap_check &&
               (std::fabs(r1 - 2.0) < 1e-9 && std::fabs(r2 - 3.0) < 1e-9);
    cases.push_back({
        "branching_and_quadratic_roots",
        lab::jbool(true),
        lab::jbool(ok2),
        ok2
    });

    // Case 3: Natural sum, factorial, GCD, LCM, triangle pattern
    int nat_sum = 0;
    for (int i = 1; i <= 100; ++i) nat_sum += i;
    long long fact6 = 1;
    for (int i = 2; i <= 6; ++i) fact6 *= i;
    int g = std::gcd(48, 18);
    int l = std::lcm(48, 18);
    std::ostringstream tri;
    for (int r = 1; r <= 4; ++r) {
        tri << std::string(static_cast<std::size_t>(r), '*') << "\n";
    }
    bool ok3 = (nat_sum == 5050) && (fact6 == 720) &&
               (g == 6 && l == 144) &&
               (tri.str() == "*\n**\n***\n****\n");
    cases.push_back({
        "loops_factorial_gcd_lcm_triangle",
        lab::jbool(true),
        lab::jbool(ok3),
        ok3
    });

    // Case 4: Simple calculator & 10-day monkey-peach problem
    bool calc_ok = (std::fabs(lab::calc(12, '+', 3) - 15.0) < 1e-9) &&
                   (std::fabs(lab::calc(12, '-', 3) - 9.0) < 1e-9) &&
                   (std::fabs(lab::calc(12, '*', 3) - 36.0) < 1e-9) &&
                   (std::fabs(lab::calc(12, '/', 3) - 4.0) < 1e-9);
    int peaches = 1;
    for (int day = 9; day >= 1; --day) {
        peaches = (peaches + 1) * 2;
    }
    bool ok4 = calc_ok && (peaches == 1534);
    cases.push_back({
        "calculator_and_monkey_peaches",
        lab::jbool(true),
        lab::jbool(ok4),
        ok4
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-examples-lab/explore-cpp-examples.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-examples.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2322.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习