0

I have this code and the function pow() is behaving differently in two cases.

For "p" I'm using the number 3, in the first output is showing 124 but the second shows 125.

#include <iostream>
#include <math.h>
using namespace std;

int main(){

    long long int p, ans;
    cin >> p; //3

    ans = pow(5,p);

    cout << ans << endl; //124

    cout << pow(5,p) << endl; //125
    return 0;
}
Everaldo
  • 55
  • 8
  • Since `ans` is `long long int`, the `ans = pow(5,p);` will truncate. Maybe you wanted it to round? – Eljay Feb 03 '20 at 15:01
  • `pow(5,p)` is not an integer. Print all the digits: `cout << setprecision(100) << pow(5,p)`. (And `#include `.) Then think about the difference between rounding and truncation. – molbdnilo Feb 03 '20 at 15:01
  • Short answer is - never rely on floating point operations to have precise results. Implement pow function on your own (with a simple loop or [more advanced algorithm](https://stackoverflow.com/questions/20923780/how-to-explain-this-algorithm-for-calculating-the-power-of-a-number)). – Yksisarvinen Feb 03 '20 at 15:03

0 Answers0