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

标签 c pow exponentiation

<分区>

我只是在编写一个程序来计算整数的幂。但是输出并不像预期的那样。它适用于除 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.5pow 的返回值然后将其转换为 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;
}

关于c - pow() 是否适用于 C 中的 int 数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818160/

相关文章:

c++ - 在表达式中使用 pow 函数

Python 实现 pow() 通过对非常大的整数进行平方来求幂

iphone - “html agility pack” 类似 C/Objective-c/iPhone 的解决方案

c - B 和 *B 如何在 C 中返回相同的地址?

c - 在C中,将指向字符串的指针从函数传递到主函数的正确方法是什么

c - 使用通用字段初始化结构的通用 API

Python 3 : RuntimeWarning with numpy. 电源

c - 这个C程序有什么问题?

c++ - C++ 中的大指数