C++ 64位整型输出问题
阿神
阿神 2017-04-17 11:36:17
[C++讨论组]

这样一段代码:求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的默认输出范围不够吗?怎么解决?

阿神
阿神

闭关修行中......

全部回复(2)
天蓬老师

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

PHP中文网

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 才稳当

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号