17. C上的数字后截断 [英] Truncation after 17. Digit on C

查看:146
本文介绍了17. C上的数字后截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 C 上编写一个有关国王,棋盘和米粒之间的经典历史的简单程序.填充棋board所需的米粒总量为: 18 446 744 073 709 551 615 .

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 .

但是我得到了: 18 446 744 073 709709552 000 .在C上.

But i'm getting : 18 446 744 073 709 552 000. on C.

是否没有解决方案来提高17位数字的分辨率?

Aren't there any solution to increase 17 digits resolution?

这是我的代码.

#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;
}

提前谢谢!

推荐答案

double的精度约为17个十进制数字(52位+1).因此您将使用具有64位或更高精度的类型.

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;
}


如果long double的准确度大于double


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;
}

这篇关于17. C上的数字后截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆