首页 > C++ 64位整型输出问题

C++ 64位整型输出问题

这样一段代码:求1到n的累加和。

#include<iostream>
using namespace std;
int main(){
    int n;   
    cin>>n;
    cout<<(n*n+n)/2;
    return 0;
}

当n取一个很大的数,比如1000000000时,发现输出的是一个负数。
而且我试着定义一个64位整型变量:

long long s = (n*n+n)/2;
cout<<s;

依然输出负数。
是cout的默认输出范围不够吗?怎么解决?


C++的数据类型,除了 char 是精确定义为 1字节 大小之外,其它数据的大小都是不确定的,能确定的只有最小值,关于这一点,可以 参考这里

这个表格列出了各种数据类型以及它们的大小,并且在后面有一个说明:

Note in the panel above that other than char (which has a size of exactly one byte), none of the fundamental types has a standard size specified (but a minimum size, at most). Therefore, the type is not required (and in many cases is not) exactly this minimum size. This does not mean that these types are of an undetermined size, but that there is no standard size across all compilers and machines; each compiler implementation may specify the sizes for these types that fit the best the architecture where the program is going to run. This rather generic size specification for types gives the C++ language a lot of flexibility to be adapted to work optimally in all kinds of platforms, both present and future.

大概意思是说 char 的大小是精确定义的,其它类型按顺序一个比一个大(或等),但其大小都是不确定的,由编译器根据不同的架构(指CPU)等因素定义。

根据这个说明,如果你想使用 64 位的整数,定义成 long long 才稳当


n 的类型需要是 long long 才行。

【热门文章】
【热门文章】