pow() 是否适用于 C 中的 int 数据类型?

Does pow() work for int data type in C?

我只是在写一个程序来计算整数的幂。但是输出并不像预期的那样。它适用于除 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() 函数吗??

C 库函数 double pow(double x, double y)

需要double类型

没有基于 int 的 pow。您遇到的是浮点截断问题。

基于 int 的 pow 过于受限(输入的范围会很快溢出 int)。在许多情况下,基于 int 的 pow,就像你的情况一样,它的 2 的幂可以通过其他方式有效地完成。

printf("%a", pow(10, 2)) 看看你得到了什么;我希望你会看到你 相当 得到 100。如果你想舍入而不是截断,请调用 lround

浮点精度在这里发挥作用。 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 的 return 值,然后将其转换为 int

b = (int)(pow(a,2) + 0.5);  

所以,你的问题的答案

Does pow() work for int data type in C?

不总是。对于整数求幂,您可以实现自己的函数(这仅适用于 0 和 +ve exp):

int int_pow(int base, int exp)
{
    int result = 1;
    while (exp)
    {
        if (exp % 2)
           result *= base;
        exp /= 2;
        base *= base;
    }
    return result;
}