返回首页 C++ 模板

数据类型转换模板

隐式转换与强制转换——理解 C++ 类型提升规则

类型转换 隐式转换 强制转换 GESP2
#include <bits/stdc++.h>
using namespace std;

int main() {
    // 隐式转换:小类型→大类型
    int a = 5;
    double b = a;        // int → double,5.0
    cout << b << endl;

    // 隐式转换:算术运算中低精度→高精度
    cout << 5 / 2 << endl;       // 2(int/int)
    cout << 5.0 / 2 << endl;     // 2.5(double/int → double)
    cout << 5 / 2.0 << endl;     // 2.5

    // 强制转换
    double pi = 3.14159;
    int piInt = (int)pi;          // C 风格
    int piInt2 = int(pi);         // 函数风格
    cout << piInt << " " << piInt2 << endl;  // 3 3

    // 赋值时的截断
    double d = 3.99;
    int n = d;            // 截断为 3,不是四舍五入!
    cout << n << endl;

    // char 与 int 互转
    char ch = 'A';
    int ascii = ch;       // 65
    char ch2 = 66;        // 'B'
    cout << ascii << " " << ch2 << endl;

    // 四舍五入技巧
    double val = 3.6;
    int rounded = (int)(val + 0.5);  // 正数四舍五入
    cout << rounded << endl;  // 4

    return 0;
}

📖 要点说明

⚠️ 常见错误