zoukankan      html  css  js  c++  java
  • C标准库pow函数精度问题。

    #include <stdio.h>
    int main ()
    {
    int temp,i;
    double a=2.4568;
    unsigned char b[5];
    for(i=0;i<5;i++)
    {
    temp=(int)a; 
    b[i]=temp+'0';
    a=(a-temp)*10;
    printf("%f %d
    ",a,(int)a);
    }
    b[5]='';
    puts(b);
    }

    运行结果:

    运行结果:
    4.568000 4
    5.680000 5
    6.800000 6
    8.000000 7
    10.000000 9
    24567
    --------------------------------
    Process exited with return value 0
    Press any key to continue . . .
    为什么最后的8.00000和10.00000被强制转换成7和9而不是8和10;

    首先 float double这类的数据是近似值 有精度问题 这一点你知道吧

    也就是说打印出来的8.0000 未必是8.00000

    在你这个例子里面 

    我改了一下 改为打印出20位小数:

    #include <stdio.h>
    int main ()
    {
         int temp,i;
         double a=2.4568;
        unsigned char b[5];
     for(i=0;i<5;i++)
     {
             temp=(int)a;    
             b[i]=temp+'0';
              a=(a-temp)*10;
              printf("%.20f %d
    ",a,(int)a);
     }
             b[5]='';
             puts(b);
    }

    你再运行一下看看

    可以发现8.00000实际上是7.99999999999872812850 所以会是转为int的7

    一般来说 要把浮点转为int 要取得最近似的值 都是采用(int)(a+0.5) 从而达到一种四舍五入的效果

  • 相关阅读:
    c++ 迷宫问题
    linux下恢复删除的文件
    c++ 分解数2
    c++ 平分石头
    多态
    设计模式中类的6种关系
    工厂方法模式
    设计原则之面向接口编程
    封装、继承
    便利构造器、单件模式
  • 原文地址:https://www.cnblogs.com/VIPler/p/6910731.html
Copyright © 2011-2022 走看看