【发布时间】:2016-03-26 18:32:02
【问题描述】:
我编写了一个程序,将一个数字拆分为多个数字,当它们相加时,给出第一个数字。例如,1234 应拆分为 1000、200、30 和 4。
#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
如您所见,这是不正确的,为什么?
【问题讨论】:
-
你发布的版本似乎和ideone.com/K3pY8r一样工作
-
因为
pow包含一个浮点表示错误。 -
我在多个在线编译器上尝试过,它确实有效,但它在我的 PC 上不起作用。如何避免该错误?
-
如果需要精确值,请不要使用浮点数。
-
那么为什么会出现这个错误,如何去掉浮点数呢?