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").
链接地址: http://www.djcxy.com/p/69878.html上一篇: 第19行的语法错误
下一篇: 在c ++中存储和打印10+数字整数