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) 从而达到一种四舍五入的效果

原文地址:https://www.cnblogs.com/VIPler/p/6910731.html