我只是在编写一个程序来计算整数的幂。但是输出并不像预期的那样。它适用于除 5 的幂
之外的所有整数。
我的代码是:
#include <stdio.h>
#include <math.h>
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
图书馆说:
### <math.h>
/* Excess precision when using a 64-bit mantissa for FPU math ops can
cause unexpected results with some of the MSVCRT math functions. For
example, unless the function return value is stored (truncating to
53-bit mantissa), calls to pow with both x and y as integral values
sometimes produce a non-integral result. ... */
只需添加 0.5
到 pow
的返回值然后将其转换为 int
.
b = (int)(pow(a,2) + 0.5);
所以,你的问题的答案
Does pow() work for int
data type in C?
并不总是。对于整数求幂,您可以实现自己的函数(这仅适用于 0 和 +ve exp
):
unsigned uint_pow(unsigned base, unsigned exp)
{
unsigned result = 1;
while (exp)
{
if (exp % 2)
result *= base;
exp /= 2;
base *= base;
}
return result;
}