C问题中的pow()函数 [英] pow() function in C problems
问题描述
我在C中使用pow()
函数时遇到了一些问题.只要运行此代码153
作为输入,总和就等于152
.但是,如果我不使用pow()
函数,而是使用for
循环来获取 N n 的值,则求和结果为153
.有人可以帮我解释一下这种区别吗?
I am having some problems with pow()
function in C. When ever run this code, 153
as input, the sum evaluates to 152
. However if I dont use pow()
function and instead use a for
loop to get the value of Nn, the sum evaluates to 153
. Can anyone help please explain me this difference?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
unsigned int i, n, sum = 0, N, a = 1, j;
char num[100], x[2] = { 0 };
printf("Determining an armstrong number\n\n"
"Enter a number: ");
fflush(stdin);
gets(num);
n = strlen(num);
for (i = 0; i < n; i++) {
a = 1;
x[0] = num[i];
N = atoi(x);
/* for (j = 1; j <= n; j++)
a *= N;
*/
sum += pow(N, n);
}
n = atoi(num);
if (sum == n)
printf("\nIt is an Armstrong number!\n");
else
printf("\nIt is not an Armstrong number!\n");
return 0;
}
推荐答案
您的C实现(包括其数学库)对pow
的实现不正确,导致返回的结果不准确. (当数学结果可以用浮点格式精确表示时,好的pow
实现将返回精确结果.)例如,对于pow(7, 2)
,您的pow
可能返回的值略低于49.转换为unsigned int
(除了sum
之外),它被截断,结果为48.
Your C implementation, including its math library, has a bad implementation of pow
that returns inaccurate results. (A good pow
implementation returns an exact result when the mathematical result is exactly representable in the floating-point format.) For example, for pow(7, 2)
, your pow
may be returning a value slightly under 49. When this is converted to an unsigned int
(in the addition to sum
), it is truncated, resulting in 48.
要变通解决此库中的此缺陷,请不要对整数运算使用pow
.编写自己的整数运算以获得所需的结果.在某些情况下,使用round(pow(N, n))
可能就足够了,但是要考虑到可以使用的值的范围(宽整数可能能够表示double
无法实现的整数),有时还需要考虑性能. (另一种解决方法是获得更好的C实现.)
To work around this defect in your library, do not use pow
for integer arithmetic. Write your own integer arithmetic to get the result you desire. In some circumstances, using round(pow(N, n))
may suffice, but there are considerations of the range of values for which this will work (wide integers may be able to represent integers that double
cannot) and sometimes performance. (Another workaround is to get a better C implementation.)
这篇关于C问题中的pow()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!