输出错了幂函数 - Ç [英] wrong output by power function - C

查看:164
本文介绍了输出错了幂函数 - Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

POW()函数是给非常奇怪的输出。

pow() function is giving very strange outputs.

我尝试过各种组合:

#include<stdio.h>
#include<math.h>
int main()
{
  int d=1;
  long long n1,n2;
  while(d<10)
  {

     n1=pow(10,d);
     n2=pow(10,d);
     d++;
     printf("%lld %lld\n",n1,n2);
  }
 }

这给了错误的输出,即99,而不是100这样的。

this gives the wrong output i.e. 99 instead of 100 and like that.

现在如果我删除的变量之一,ANS。是正确的。
如果不是D,我用一个恒定的,答是正确的。
如果我带n1和n2为双,ANS是正确的。

now if i remove one of the variables, ans. is correct. if instead of d, i use a constant, ans is correct. if i take n1 and n2 as double, ans is correct.

所以,有两个POW()与均具有变数的能力和铸造为整数是给坏输出类型的功能。
为什么这样奇怪的行为?

So having two pow() functions with both having variables as the power and type casted as integers is giving bad output. Why this strange behaviour??

推荐答案

这是与事实使得从浮点值的整数(截断小数,而不是舍入),沿的情况下 POW(X,Y)转化为 EXP(日志(X)* Y),这将产生一个结果,是不是preCISELY相同为x - 只需一个邻近近似作为一个浮点值,如99.9999996(或100.00002)为10 2

This is a case of making an integer from a floating point value (which truncates the decimals, not rounding it), along with the fact that pow(x, y) translates to exp(log(x) * y), which will produce a result that isn't PRECISELY the same as xy - just a near approximation as a floating point value, such as 99.9999996 (or 100.00002) for 102.

如果你想圆它,使用轮(POW(X,Y))

If you want to round it, use round(pow(x, y)).

这篇关于输出错了幂函数 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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