哪种数据类型用于 C++ 中的非常大的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3595247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:13:52  来源:igfitidea点击:

Which data type to use for a very large numbers in C++?

c++typeslargenumber

提问by Vaibhav

I have to store the number 600851475143in my program. I tried to store it in long long intvariable and long doubleas well but on compiling it shows the error

我必须将号码存储600851475143在我的程序中。我试图将它存储在long long int变量中,long double但在编译时显示错误

integer constant is too large for "long" type. 

I have also tried unsigned long long inttoo. I am using MinGW 5.1.6 for running g++ on windows.

我也试过unsigned long long int了。我正在使用 MinGW 5.1.6 在 Windows 上运行 g++。

What datatype should I use to store the number?

我应该使用什么数据类型来存储数字?

回答by Peter Alexander

long longis fine, but you have to use a suffix on the literal.

long long很好,但是您必须在文字上使用后缀。

long long x = 600851475143ll; // can use LL instead if you prefer.

If you leave the lloff the end of the literal, then the compiler assumes that you want it to be an int, which in most cases is a 32-bit signed number. 32-bits aren't enough to store that large value, hence the warning. By adding the ll, you signify to the compiler that the literal should be interpreted as a long long, which is big enough to store the value.

如果您将ll文字的末尾保留,那么编译器会假定您希望它是 an int,在大多数情况下它是一个 32 位有符号数。32 位不足以存储这么大的值,因此发出警告。通过添加ll,您向编译器表示应该将文字解释为 a long long,它足以存储该值。

The suffix is also useful for specifying which overload to call for a function. For example:

后缀对于指定调用函数的重载也很有用。例如:

void foo(long long x) {}
void foo(int x) {}

int main()
{
    foo(0); // calls foo(int x)
    foo(0LL); // calls foo(long long x)
}

回答by Jerry Coffin

You had the right idea with long long int(or unsigned long long int), but to prevent the warning, you need to tell the compiler that the constant is a long long int:

您对long long int(or unsigned long long int)有正确的想法,但为了防止出现警告,您需要告诉编译器该常量是 a long long int

long long int value = 600851475143LL;

Those "L"s can be lower-case, but I'd advise against it -- depending on the font, a lower-case "L" often looks a lot like a one digit ("1") instead.

那些“L”可以是小写的,但我建议不要这样做——根据字体,小写的“L”通常看起来很像一位数字(“1”)。

回答by Pierre

Have a look at the GNU MP Bignum library http://gmplib.org/

看看 GNU MP Bignum 库http://gmplib.org/