mercredi 28 septembre 2016

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

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?

Aucun commentaire:

Enregistrer un commentaire