如何在 c 程序或 c++ 中存储等于 10^18 的整数值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23445662/
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 00:27:03  来源:igfitidea点击:

How to store a integer value equal to 10^18 in c programs or c++?

c++c

提问by user3599293

How can I store a large integer value in a variable of C ? If i am declaring a with int a;it won't work. I have used this with long long int.It is not working.

如何在 C 的变量中存储大整数值?如果我声明int a;它就行不通。我用过这个。long long int它不工作。

if( a>=0 && a <= (1000000000000000000))

What to declare variable a so that it will not so any error.It should be integer.

什么声明变量 a 以便它不会有任何错误。它应该是整数。

Compiler error
integer constant is too large for long type.

回答by yizzlez

Try a unsigned long long, assuming the value is positive, it can hold up to

尝试 a unsigned long long,假设值是正数,它可以容纳

18,446,744,073,709,551,615

(VS 13) However, you must use the ULLsyntax.

(VS 13) 但是,您必须使用ULL语法。

回答by Nazar554

Lets look at this ifstatement you wrote:

让我们看看if你写的这个声明:

if( a>=0 && a <= (1000000000000000000))

1000000000000000000is too big for an integral literal so you will need a bigger literal type. You should declare aas an int64_tand do the comparion like that:

1000000000000000000对于整型文字来说太大了,所以你需要一个更大的文字类型。您应该声明a为 anint64_t并像这样进行比较:

if( a>=INT64_C(0) && a <= INT64_C(1000000000000000000))

Note that this will only work in a C99or C++11compiler when you #include <cstdint>or #include <stdint.h>

请注意,这只会在工作C99C++11编译器,当你#include <cstdint>#include <stdint.h>

Edit: in current draft of the standard you can find this sentence (2.14.2/2):

编辑:在标准的当前草案中,您可以找到这句话(2.14.2/2):

The type of an integer literal is the first of the corresponding list in Table 6 in which its value can be represented.

整数文字的类型是表 6 中相应列表中的第一个,可以在其中表示其值。

It means that compiler should use the required literal type automatically to make your literal fit. Btw I didn't see that kind of compiler.

这意味着编译器应该自动使用所需的文字类型来使您的文字适合。顺便说一句,我没有看到那种编译器。

回答by user3599293

You can use a long longto store this integer. A long longis guranteed to hold at least 64 bits.

您可以使用 along long来存储这个整数。Along long保证至少保存 64 位。

The problem with this code: if( a>=0 && a <= (1000000000000000000))is that you need to give the literal (1000000000000000000) the suffix LLif you want it to be of type long longor ULLfor unsigned long long.

这段代码的问题if( a>=0 && a <= (1000000000000000000))是:如果你希望它是 type或for ,你需要给文字 ( 1000000000000000000) 后缀。LLlong longULLunsigned long long