是否POW()在C int数据类型的工作? [英] Does pow() work for int data type in C?

查看:295
本文介绍了是否POW()在C int数据类型的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被简单地写一个程序来计算的整数的功率。但并不如预期的输出。它的工作,对于除5在电源中的所有整数。

I was simply writing a program to calculate the power of an integer. But the output was not as expected. It worked for all the integer numbers except for the power of 5.

我的code是:

#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

我们不能用 POW()为int数据类型的函数??

Can't we use pow() function for int data type??

推荐答案

浮点precision在这里做的工作。 POW 的实际工作中使用登录

Floating point precision is doing its job here. The actual working of pow is using log

pow(a, 2) ==> exp(log(a) * 2)

文件math.h 库,它说:

/ *过量precision可以
  导致一些MSVCRT数学函数意想不到的效果。对于
  例如,除非该函数返回值被存储(截断到
  53位尾数),调用与x和y作为积分值战俘
  有时产生非整结果。 ... * /

/* 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

Just add 0.5 to the return value of pow and then convert it to int.

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

所以,回答你的问题。

So, the answer to your question

请问POW()为 INT 工作数据类型用C?

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

并非总是如此。对于整数幂,你可以实现自己的功能(这将连续工作+已经只能为整数):

Not always. For integer exponentiation you could implement your own function (this will work for +ve integers only):

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

这篇关于是否POW()在C int数据类型的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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