Why a+=b*pow(10,c-i-1) == 99 c++? [duplicate]

南笙酒味 提交于 2019-12-19 04:46:32

问题


I wrote this code and first time of loop result is 99. Why is result 99, when it should be 100?

#include <iostream>
#include<math.h>
using namespace std;
int main ()
{
  int skt = 0;
  int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
    skt = skt + (sk[i]*pow(10.0,nsk-i-1));
    cout <<" "<<skt<<endl;
}

}

the result of this code

   99
   119
   127

,but if I use library cmath it is correct answer

#include <iostream>
#include<cmath>
using namespace std;
int main ()
{
  int skt = 0;
  int sk[3];
int nsk = 3;
sk[0]=1;
sk[1]=2;
sk[2]=8;
for (int i=0; i<nsk; i++)
{
    skt = skt + (sk[i]*pow(10.0,nsk-i-1));
    cout <<" "<<skt<<endl;
}

}

the result of this code

    100
    120
    128

Could anybody explain why?


回答1:


The math.h and cmath versions of pow are slightly different. Basically there are more supported inputs for the cmath version. You can compare the two at these links.

math.h and cmath




回答2:


As people have commented, it's probably related to variable type conversion and floating point errors. Pow operates on doubles, which can have floating point errors. Chances are pow is returning a value like 99.9999999 which is then being converted to an integer. Since the integer conversion truncates instead of rounds, you get 99.




回答3:


from this link cplusplus.com

Additional overloads are provided in this header ( cmath ) for other combinations of arithmetic types (Type1 and Type2): These overloads effectively cast its arguments to double before calculations, except if at least one of the arguments is of type long double (in which case both are casted to long double instead).

I bet if you cast it it would be correct in math.h



来源:https://stackoverflow.com/questions/39756656/why-a-bpow10-c-i-1-99-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!