问题
I was trying to write a simple program on C about the classical history between the king, chessboard and rice grains. The total amount of rice grains that is needed to fill the chessboard is : 18 446 744 073 709 551 615 .
But i'm getting : 18 446 744 073 709 552 000. on C.
Aren't there any solution to increase 17 digits resolution?
Here is my code.
#include <stdio.h>
#include <math.h>
int main( void )
{
double i=1.0;
while(i<=64)
{
printf("%2.0lf.Casilla = %.0lf\n", i, pow(2.0,(i-1.0)));
i++;
}
printf("\n\n***En Total = %.0lf Granos.\n\n",pow(2.0,64.0)-1);
return 0;
}
Thanks in advance!
回答1:
double
of accuracy is approximately 17 decimal digits(52bit+1). so You'll use the type that has a 64-bit or higher accuracy.
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
uint64_t pow_2_i(int n){//2^n
if(0 > n || n >= 64)
return 0;
uint64_t x = 1;
return x << n;
}
int main(void){
int i;
uint64_t x, sum = 0;
for(i = 1; i <= 64; ++i){
sum += (x = pow_2_i(i-1));
printf("%2d.Casilla = %" PRIu64 "\n", i, x);
}
printf("\n\n***En Total = %" PRIu64 " Granos.\n\n", sum);//No Cheat^-^
return 0;
}
If long double
has large accuracy than double
#include <stdio.h>
int main( void ){
long double x=1.0;//1.0L
int i;
for(i=1; i<=64;++i){
printf("%2d.Casilla = %.0Lf\n", i, x);
x *= 2.0L;
}
printf("\n\n***En Total = %.0Lf Granos.\n\n", x-1.0L);//2^64-1:Σar^k (k=0->n) =a(r^(n+1)-1)/(r-1):1(2^(63+1)-1)/(2-1)
return 0;
}
来源:https://stackoverflow.com/questions/29388592/truncation-after-17-digit-on-c