pow()是否适用于C中的int数据类型?
我只是编写一个程序来计算整数的幂。 但产量不如预期。 除了5的幂之外,它适用于所有整数。
我的代码是:
#include #include int main(void) { int a,b; printf("Enter the number."); scanf("\n%d",&a); b=pow(a,2); printf("\n%d",b); }
输出是这样的:
"Enter the number. 2 4 "Enter the number. 5 24 "Enter the number. 4 16 "Enter the number. 10 99
我们不能对int数据类型使用pow()
函数吗?
浮点精度正在这里发挥作用。 pow
的实际工作是使用log
pow(a, 2) ==> exp(log(a) * 2)
看看math.h
库说:
/ *使用64位尾数进行FPU数学运算时的精度过高会导致某些MSVCRT数学函数出现意外结果。 例如,除非存储函数返回值(截断为53位尾数),否则将x和y作为整数值的pow调用有时会产生非整数结果。 …… * /
只需在pow
的返回值中加0.5
,然后将其转换为int
。
b = (int)(pow(a,2) + 0.5);
那么,你的问题的答案
pow()是否适用于C中的
int
数据类型?
不总是。 对于整数取幂,您可以实现自己的函数(这仅适用于+ ve整数):
int int_pow(int base, int exp) { int result = 1; while (exp) { if (exp & 1) result *= base; exp /= 2; base *= base; } return result; }
没有基于int的战俘。 你所遭受的是浮点截断。
基于int的pow太受约束(输入范围会快速溢出int)。 在许多情况下基于int的pow,就像你的情况一样,2的权力可以通过其他方式有效地完成。
C库函数双pow(双x,双y)
它需要双重类型
printf("%a", pow(10, 2))
并看看你得到了什么; 我希望你看到你不会得到100。如果你想要圆形而不是截断,请调用lround
。