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

发布于 2024-09-16 13:56:10 字数 321 浏览 20 评论 0原文

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

integer constant is too large for "long" type. 

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

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

I have to store the number 600851475143 in my program. I tried to store it in long long int variable and long double as well but on compiling it shows the error

integer constant is too large for "long" type. 

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

What datatype should I use to store the number?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

晨与橙与城 2024-09-23 13:56:10

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

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

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

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

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

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

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

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

If you leave the ll off 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.

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)
}
我偏爱纯白色 2024-09-23 13:56:10

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

long long int value = 600851475143LL;

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

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 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.

眼藏柔 2024-09-23 13:56:10

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文