简体   繁体   中英

Storing and printing 10+ digit integer in c++

I'm using cout to print digits to the console. I am also storing values of up to 13+billion as a digit and doing computations on it. What data type should I use?

When I do the following:

int a = 6800000000;
cout << a;

It prints -1789934592.

thanks.

long long最多可以容纳 9223372036854775807。如果需要更大的,请使用gmp东西。

Use int64_t to guarantee you won't overflow. It is available from stdint.h .

Just a note that both int64_t and long long are included in C99 and in C++ 0x, but not in the current version of C++. As such, using either does put your code at some risk of being non-portable. Realistically, however, that risk is probably already pretty low -- to the point that when/if you port your code, there are likely to be much bigger problems.

If, however, you really want to assure against that possibility, you might consider using a double precision floating point. Contrary to popular belief, floating point types can represent integers exactly up to a certain limit -- that limit being set (in essence) by the size of the mantissa in the FP type. The typical implementation of a double has a 53-bit mantissa, so you can represent 53-bit integers with absolute precision. That supports numbers up to 9,007,199,254,740,992 (which is substantially more than 13 of either of the popular meanings of "billion").

Your data type (int) is too small to hold such large numbers. You should use a larger data type or one of the fixed size data types as given in the other answer (though you should really use uint64_t if you're not using negative numbers).

It's a good idea to understand the range limits of different sized types.

A 32 bit type (on most 32 bit platforms, both int and long are 32 bit) have the following ranges:

signed: -2,147,483,648 to 2,147,483,647
unsigned: 0 to 4,294,967,295

While 64 bit types (typically long long's are 64 bit, on most Unix 64 bit platforms a long is also 64) have the following range:

signed: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned: 0 to 18,446,744,073,709,551,615

只需在声明语句中使用 double

unsigned long long

can be used

You could use a long int:

long int a

Or if it's always going to be positive, an unsigned long int:

unsigned long int a

See: http://forums.guru3d.com/showthread.php?t=131678

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM