-1

I've written this code:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int x,n,result;

    cout<<"enter the value"<<endl;
    cin>>x;

    cout<<"enter the power"<<endl;
    cin>>n;

    result=pow(x,n);
    cout<<"the result of power\t"<<x<<"to\t"<<n<<"=\t"<<result;
}

When I assign x=10 n=2 the result is 99 not 100.
When i change x,n,result to float type, the output is x=10 n=2 result=100.

Can someone explain me why this difference?

mtszkw
  • 2,717
  • 2
  • 17
  • 31
saif faez
  • 59
  • 1
  • 7
  • 2
    First learn that [`pow`](http://en.cppreference.com/w/cpp/numeric/math/pow) is a *floating point* function, then see that [floating point math is *not* broken](http://stackoverflow.com/q/588004/440558). – Some programmer dude Aug 28 '15 at 11:29
  • You're (unknowingly) using floating point calculations. Converting floating point numbers to integers is a source of errors. If you instead printed `pow(x,n)` directly you would get a more reasonable answer. – skyking Aug 28 '15 at 11:45

1 Answers1

0

How about reading C++ reference? Here is what you can find about pow():

double pow (double base, double exponent);
float pow (float base, float exponent);
long double pow (long double base, long double exponent);
double pow (Type1 base, Type2 exponent); // additional overload

As you can see, there is no pow() for integer arguments, but you may use casting, like:

int x, n;  
{...}  
double result=pow(double(x),double(n));

More informations were written here: Why is my integer math with std::pow giving the wrong answer?

Community
  • 1
  • 1
mtszkw
  • 2,717
  • 2
  • 17
  • 31