1. 程式人生 > >C標準庫pow函數精度問題。

C標準庫pow函數精度問題。

一般來說 nbsp any pre 4.5 logs urn padding signed

#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) 從而達到一種四舍五入的效果

C標準庫pow函數精度問題。