温馨提示×

如何使用C++ limits查询数据类型范围

c++
小樊
81
2024-09-12 19:46:57
栏目: 编程语言

在 C++ 中,您可以使用` 头文件来查询数据类型的范围

#include<iostream>
#include<limits>

int main() {
    // 查询 int 类型的最小值和最大值
    std::cout << "int 类型的最小值: "<< std::numeric_limits<int>::min()<< std::endl;
    std::cout << "int 类型的最大值: "<< std::numeric_limits<int>::max()<< std::endl;

    // 查询 float 类型的最小值和最大值
    std::cout << "float 类型的最小值: "<< std::numeric_limits<float>::min()<< std::endl;
    std::cout << "float 类型的最大值: "<< std::numeric_limits<float>::max()<< std::endl;

    // 查询 double 类型的最小值和最大值
    std::cout << "double 类型的最小值: "<< std::numeric_limits<double>::min()<< std::endl;
    std::cout << "double 类型的最大值: "<< std::numeric_limits<double>::max()<< std::endl;

    return 0;
}

在这个示例中,我们使用 std::numeric_limits 模板类来获取不同数据类型的最小值和最大值。请注意,对于浮点类型(如 float 和 double),min() 返回的是正的最小规范化值,而不是负的最大值。要获取浮点类型的负最大值,可以使用 -max()

运行此程序将输出各种数据类型的最小值和最大值。

0