幂函数少返回1个结果 [英] Power function returns 1 less result

查看:102
本文介绍了幂函数少返回1个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我在该程序中输入数字时,程序都会返回一个比实际结果小1的值...这是什么问题?

Whenever I input a number in this program the program return a value which is 1 less than the actual result ... What is the problem here??

#include<stdio.h>
#include<math.h>
 int main(void)
 {
     int a,b,c,n;

     scanf("%d",&n);

     c=pow((5),(n));

    printf("%d",c);

 }

推荐答案

pow ()返回 double ,即从 double int 正在向零舍入。

pow() returns a double, the implicit conversion from double to int is "rounding towards zero".

因此,这取决于 pow()的行为函数。

So it depends on the behavior of the pow() function.

如果完美,那么没问题,转换是准确的。

If it's perfect then no problem, the conversion is exact.

如果没有:

1)结果稍大,那么转换会将其舍入到期望值。

1) the result is slightly larger, then the conversion will round it down to the expected value.

2)如果结果稍小一点,那么转换将舍入为您所看到的。

2) if the result is slightly smaller, then the conversion will round down which is what you see.

解决方案:

使用舍入函数将转换转换为四舍五入到最接近的整数

c=lround(pow((5),(n)));

在这种情况下,只要 pow()的误差小于+ -0.5,您将获得预期的结果。

In this case, as long as pow() has an error of less than +-0.5 you will get the expected result.

这篇关于幂函数少返回1个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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