Suppose i want to store 2^100 in a variable. No integer type allows this. But this can be stored in a double variable with zeros after the decimal point i.e the following code may be used.
double no = 1;
int i = 1;
for(i=1;i<=100;i++) no*=2;
I now want to print 'no' without what is there after decimal point. Can this be done. I'm just interested in printing and not its storage.
Note: I know the problem can be done using array of integer,so please don't suggest that method.
You are talking about arbitrary precision integers for which I would advice to use a library such as GMP. See https://gmplib.org.
Using floating point numbers will not solve your problem because it will round your integer to the closest floating point number and you will lose precision.
"On a typical computer system, a 'double precision' (64-bit) binary floating-point number has a coefficient of 53 bits (one of which is implied), an exponent of 11 bits, and one sign bit." (Wikipedia)
As long as we only deal with powers of 2 then the floating point representation is exact: One significant digit (1) and an exponent equal to 100. So you can get away with using a double. Once you add any number small enough in comparison with the stored number, you are left with the original number as a result. Classic floating point issues.
You say C++, but this is much easier to do with C I/O (which you can use in C++, but its not really C++). You just want to print in f format with no digits after the decimal:
printf("%.0f\n", no);
In C++ you can do the same with:
std::cout << std::fixed << std::setprecision(0) << no << std::endl;
which is much more verbose, and has persistent effects on later things printed...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With