简体   繁体   中英

How to use the Class function in C++ to save large numbers

I am creating a C++ program on Astronomy and the numbers are too big for any integer type to keep. I found out some articles that they pointed out that it can be done using the class function. The numbers I am dealing with is like a few hundred thousands of light years converted into kilometers, so the number is something like 3.081814457932196587132947576e+27. Any ideas how to save such a large number?

If you really need that many significant digits in floating point format, you should probably look at a well-known library like MPFR .

If you don't need floating point, take a look at the de-facto standard multi-precision library GMP (which MPFR itself is based on).

Note that both are C libraries. GMP has some C++ bindings/wrappers, but not everything is wrapped, so you'll still need to call the C functions for all but the most basic arithmetic. Same goes for MPFR (there's a bunch of C++ wrappers listed on their site).

If you only want to handle integers it's quite simple.

You can store your numbers into arrays, like :

big_num = [3, 0, 8, 1, 8, 1, 4, 4, 5, 7, 9, 3, 2, 1, 9, 6, 5, 8, 7, 1, ... 6]

At each index of the array you have one digit

You can implement yourself the computation functions, or you can use a big num lib like :

https://github.com/kokke/tiny-bignum-c

https://www.di-mgt.com.au/bigdigits.html

https://gmplib.org/

I sure you can find the lib which will realy suits you on the internet. :)

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