C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > c++ int、 long int、long long int取值

c++中int、 long int、long long int的取值范围

作者:bu_shuo

本文主要介绍了c++中int、 long int、long long int的取值范围,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

问题描述

在刷Leetcode或者牛客网的过程中, 题目的描述中经常会限制数据的取值范围, 所以在编写代码的过程中非常有必要注意, 否则选择不合适的变量类型将无法通过部分测试案例.

cpp中一些变量的取值范围

#include <iostream>
#include <climits>
using namespace std;

int main() {
    cout << "=== C++ 整数类型取值范围 ===" << endl;

    cout << "int:                " << INT_MIN << " ~ " << INT_MAX << endl;
    cout << "unsigned int:       0 ~ " << UINT_MAX << endl;
    cout << "long int:           " << LONG_MIN << " ~ " << LONG_MAX << endl;
    cout << "unsigned long int:  0 ~ " << ULONG_MAX << endl;
    cout << "long long int:      " << LLONG_MIN << " ~ " << LLONG_MAX << endl;
    cout << "unsigned long long: 0 ~ " << ULLONG_MAX << endl;

    cout << "\n=== 各类型占用字节数 ===" << endl;
    // table键对齐.
    cout << "int:                " << sizeof(int) << " bytes" << endl;
    cout << "unsigned int:       " << sizeof(unsigned int) << " bytes" << endl;
    cout << "long int:           " << sizeof(long int) << " bytes" << endl;
    cout << "unsigned long int:  " << sizeof(unsigned long int) << " bytes" << endl;
    cout << "long long int:      " << sizeof(long long int) << " bytes" << endl;
    cout << "unsigned long long: " << sizeof(unsigned long long) << " bytes" << endl;

    return 0;
}

程序运行结果

=== C++ 整数类型取值范围 ===
int:                -2147483648 ~ 2147483647
unsigned int:       0 ~ 4294967295
long int:           -9223372036854775808 ~ 9223372036854775807
unsigned long int:  0 ~ 18446744073709551615
long long int:      -9223372036854775808 ~ 9223372036854775807
unsigned long long: 0 ~ 18446744073709551615

=== 各类型占用字节数 ===
int:                4 bytes
unsigned int:       4 bytes
long int:           8 bytes
unsigned long int:  8 bytes
long long int:      8 bytes
unsigned long long: 8 bytes

常见输出结果(64位系统下)

类型字节数取值范围
int4-2,147,483,648 ~ 2,147,483,647 (2.1*10^9)
unsigned int40 ~ 4,294,967,295
long int4 或 8取决于平台(Windows 4字节, Linux 8字节)
unsigned long int4 或 8取决于平台
long long int8-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807
unsigned long long80 ~ 18,446,744,073,709,551,615

关键知识点

结论

一般情况下, 使用int类型已经足够了.

到此这篇关于c++中int、 long int、long long int的取值范围的文章就介绍到这了,更多相关c++ int、 long int、long long int取值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文