我在Windows XP上运行了以下两段代码(代码:Block,MinGW)和Ubuntu(11.04,G ++)
我无法运行以下代码
#include <iostream>
using namespace std;
int main(){
long long a = 9223372036854775807;
cout << a;
return 0;
}
这个数字是2 ^ 63 -1。但我会收到一个错误说明:
C:\ Documents and Settings \ JohnWong \ My Documents \ codeblock \ 343_hw_1 \ main.cpp | 9 |错误:整数常量也是 大“长”型|
关于ubuntu - 它编译了,但回复的回答是9223372036854775808,注意结尾的8 ....
现在如果我运行此代码,使用power函数,我没关系。
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main(){
long long a = pow(2,64);
cout << "a: " << setprecision(20) << a << endl;
cout << "a-1: " << setprecision(20) << a-1 << endl;
cout << "a-2: " << setprecision(20) << a-2 << endl;
cout << "a+0: " << setprecision(20) << a+0 << endl;
cout << "a+1: " << setprecision(20) << a+1 << endl;
cout << "a+2: " << setprecision(20) << a+2 << endl;
cout << "a+3: " << setprecision(20) << a+3 << endl;
return 0;
}
我会得到我想要的值(+1中的任何内容都会导致溢出,这没关系。)
在Ubuntu上,输出看起来一样。好。
那么这里发生了什么?为什么常数不好??? 我甚至尝试使用intmax_t和int64_t作为运行第一个代码的数据类型。
有人可以解释这种行为吗?谢谢!
答案 0 :(得分:13)
long long a = 9223372036854775807LL;
LL使文字成为长文字。否则,文字默认为长文字,然后在存储到a之前将其转换为很长时间。
答案 1 :(得分:2)
在C ++ 11之前,C ++语言没有long long
类型。您的编译器显然不是C ++ 11编译器,它支持long long
作为扩展。这就是编译器发出警告的原因。它警告你,文字是以非标准(扩展)方式解释的,即在搜索文字的适当类型时,编译器必须超出语言标准的范围。