【发布时间】:2018-06-30 07:04:44
【问题描述】:
我在 C 中使用 pow() 函数时遇到了一些问题。当运行此代码时,153 作为输入,总和计算结果为 152。但是,如果我不使用pow() 函数而是使用for 循环来获取Nn 的值,则总和的计算结果为153。谁能帮我解释一下这个区别?
#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;
}
【问题讨论】:
-
fflush(stdin);--> UBgets--> 不要使用它 -
不要使用
pow进行整数幂计算。 -
另请参阅stackoverflow.com/questions/41072787/why-is-powint-int-so-slow,了解如何计算 pow()
标签: c floating-point floating-accuracy pow