您的位置:首页 > 其它

C标准库pow函数精度问题。

2017-05-26 22:35 197 查看
#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\n",a,(int)a);
}
b[5]='\0';
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\n",a,(int)a);
}
b[5]='\0';
puts(b);
}

你再运行一下看看 可以发现8.00000实际上是7.99999999999872812850 所以会是转为int的7 一般来说 要把浮点转为int 要取得最近似的值 都是采用(int)(a+0.5) 从而达到一种四舍五入的效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: