编译运行:clang++ -std=c++26 -Wall -Wextra -pthread 测试_第02章_变量与类型.cpp -o t && ./t(需先 cd 测试/)
// 第2章测试:变量与类型
#include <print>
#include <string>
#include <limits>
#include <type_traits>
#include <cmath>
int failures = 0;
#define CHECK(expr) \
do { \
if (!(expr)) { \
++failures; \
std::println("FAIL 第{}行: {}", __LINE__, #expr); \
} \
} while (0)
constexpr int square(int n) { return n * n; }
int main() {
// 2.2 整数类型与溢出
int big = std::numeric_limits<int>::max();
CHECK(big + 1 == std::numeric_limits<int>::min()); // 溢出绕一圈
long long ll = 1'000'000'000'000LL; // 数字分隔符 C++14
CHECK(ll == 1'000'000'000'000LL);
CHECK(sizeof(int) == 4);
// 2.3 浮点数
double d = 0.1 + 0.2;
CHECK(d != 0.3); // 二进制不精确
CHECK(std::abs(d - 0.3) < 1e-9); // 正确比较法
// 2.4 布尔
bool ok = true;
CHECK(ok);
CHECK(!false);
// 2.5 字符与字符串
char c = 'A';
CHECK(c + 1 == 'B');
std::string s = "你好";
CHECK(s.size() == 6); // UTF-8:一个汉字 3 字节
// 2.6 auto 推断
auto x = 42;
static_assert(std::is_same_v<decltype(x), int>);
auto y = 3.14;
static_assert(std::is_same_v<decltype(y), double>);
// 2.7 常量与 constexpr
const int MAX = 100;
// MAX = 1; // 编译错误:不可修改
CHECK(MAX == 100);
constexpr int r = square(5);
CHECK(r == 25);
// 2.8 类型转换
int t = static_cast<int>(3.9);
CHECK(t == 3); // 直接截断
double f = static_cast<double>(3);
CHECK(f == 3.0);
// 2.9 花括号初始化(不允许缩窄)
int a{5};
CHECK(a == 5);
int b{};
CHECK(b == 0);
// 2.10 引用
int n = 10;
int& ref = n;
ref = 20;
CHECK(n == 20);
if (failures == 0) std::println("全部通过");
return failures;
}