我做了一個程序,將一個數字拆分成數字,當添加時,給出第一個數字。例如,1234應分爲1000,200,30,和4使用pow()函數時的不準確性
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int i, num1, num2;
char tmp[6]; // the number will be stored here as string
int num3 = 12345; //the number
sprintf(tmp, "%d", num3); //convert to string
for(i = 0; i < strlen(tmp); i++) //check every digit
{
num1 = pow(10, strlen(tmp) - 1 - i); //every number will be multiplied by 10
//to the power of number of digits - 1 - counter
num2 = tmp[i] - '0'; //convert character to int
printf("%d\n", num1*num2); //print the number
}
return 0;
}
這是輸出:
9999
2000
297
40
5
正如你可以看到這是不正確的,爲什麼呢?
您發佈的版本似乎按原樣工作http://ideone.com/K3pY8r – xvan
因爲'pow'包含浮點表示形式的錯誤。 – BLUEPIXY
我在多個在線編譯器上試過了,它確實有效,但它在我的PC上無法正常工作。我該如何避免這種錯誤? – user3711671