为什么 pow(n,2) 在 n=5 时返回 24,使用我的编译器和操作系统? [英] Why does pow(n,2) return 24 when n=5, with my compiler and OS?

查看:32
本文介绍了为什么 pow(n,2) 在 n=5 时返回 24,使用我的编译器和操作系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    int n,i,ele;
    n=5;
    ele=pow(n,2);
    printf("%d",ele);
    return 0;
}

输出为24.

我在 Code::Blocks 中使用 GNU/GCC.

I'm using GNU/GCC in Code::Blocks.

发生了什么?

我知道 pow 函数返回一个 double ,但是 25 适合一个 int 类型,所以为什么这段代码打印一个 24 而不是 25?如果 n=4;n=6;n=3;n=2; 代码有效,但五个就不行.

I know the pow function returns a double , but 25 fits an int type so why does this code print a 24 instead of a 25? If n=4; n=6; n=3; n=2; the code works, but with the five it doesn't.

推荐答案

这是这里可能发生的事情.您应该能够通过查看编译器对 pow 函数的实现来确认这一点:

Here is what may be happening here. You should be able to confirm this by looking at your compiler's implementation of the pow function:

假设你有正确的#include,(之前所有关于这个的答案和评论都是正确的——不要认为 #include 文件是理所当然的),标准 pow 函数是这样的:

Assuming you have the correct #include's, (all the previous answers and comments about this are correct -- don't take the #include files for granted), the prototype for the standard pow function is this:

double pow(double, double);

然后你像这样调用 pow:

pow(5,2);

pow 函数通过算法(可能使用对数),因此使用浮点函数和值来计算幂值.

The pow function goes through an algorithm (probably using logarithms), thus uses floating point functions and values to compute the power value.

pow 函数不会通过简单的将 xa 的值乘以 n 次",因为它还必须使用分数指数计算 pow,并且你不能那样计算分数幂.

The pow function does not go through a naive "multiply the value of x a total of n times", since it has to also compute pow using fractional exponents, and you can't compute fractional powers that way.

因此很可能,使用参数 5 和 2 计算 pow 会导致轻微的舍入误差.当您分配给 int 时,您截断了小数值,从而产生了 24.

So more than likely, the computation of pow using the parameters 5 and 2 resulted in a slight rounding error. When you assigned to an int, you truncated the fractional value, thus yielding 24.

如果您使用整数,您不妨编写自己的intpow"或类似的函数,只需将值乘以所需的次数.这样做的好处是:

If you are using integers, you might as well write your own "intpow" or similar function that simply multiplies the value the requisite number of times. The benefits of this are:

  1. 您不会遇到使用 pow 可能会出现细微舍入错误的情况.

  1. You won't get into the situation where you may get subtle rounding errors using pow.

您的 intpow 函数很可能比对 pow 的等效调用运行得更快.

Your intpow function will more than likely run faster than an equivalent call to pow.

这篇关于为什么 pow(n,2) 在 n=5 时返回 24,使用我的编译器和操作系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆