1

The following code returns 99 as an output.

#include<iostream>
#include <math.h>
using namespace std;
int Solve(int a)
{
    return (pow(a,2));
}
int main()
{
    int a=10;
    cout<<Solve(a)<<endl;
    return 0;
}

I have no idea why this happens and, what is more, it does it with 5 and 25 as well, so it has something to do with multiples of 5.

P.S. is the pc broken or what :D

curiousguy
  • 8,038
  • 2
  • 40
  • 58
J.Doe
  • 39
  • 3
  • 2
    Did you try any floating point types [`std::pow`](http://en.cppreference.com/w/cpp/numeric/math/pow) is designed for? – WhozCraig Aug 15 '15 at 15:36
  • 1
    It can depend on your system. For me, it returns 100. It might be that on your system it returns 99.99999998, which will be turned into 99 when cast to int. – vsz Aug 15 '15 at 15:40

1 Answers1

4

The technical aspect: std::pow is not defined for int, only for double and float. Therefor you cannot rely on it returning the exact int value. You have to expect rounding errors.

The algorithm aspect: Calculating the n-th power using the naive algorithm (n multplications) obviously takes linear time. To improve performance for large powers, most implementations of std::pow do not use this naive algorithm. Instead they calculate the power using logarithms. This is much faster, but not as correct as the naive approach.

So if you need exact results, you have to calculate the power using a for loop.

Robin Krahl
  • 5,268
  • 19
  • 32
  • Thank you! I used it in a program where `std::pow` was called many times in a row right and when this happened it just blew my mind. – J.Doe Aug 15 '15 at 15:44
  • @J.Doe I know what you are talking about – I had `std::pow` causing a similar problem few months ago, and I was going crazy trying to debug the problem. ;-) – Robin Krahl Aug 15 '15 at 15:46