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

查看:22
本文介绍了为什么当 n=5 时 pow(n,2) 使用我的编译器和操作系统返回 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;
}

The output is 24.

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

What is happening?

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.

解决方案

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:

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);

and you're calling pow like this:

pow(5,2);

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

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.

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.

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. You won't get into the situation where you may get subtle rounding errors using pow.

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

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

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