Strange result with pow() function

Hello, I was recently making a convertor from number in base 10 to a binary number, and I ran into this problem:

(EXAMPLE CODE OF THE ISOLATED ISSUE)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;

int main()
{
    int exp = 2;
    int binary = 0;
    cout<<pow(10,exp)<<endl; //This will cout<< the number 100.
    binary += pow(10,exp);
    cout<<binary; //This will cout<< the number 99...
}


The pow function will return the number 100, but when adding the function to "binary", binary will become 99. Why does this happen? Any insight would be appreciated.
closed account (3hM2Nwbp)
If I'd have to guess, I'd say that the problem would be floating point inaccuracy. Note the pow function:


double pow (double base, double exponent );
long double pow ( long double base, long double exponent );
float pow (float base, float exponent );
double pow (double base, int exponent );
long double pow (long double base, int exponent );


To resolve this, you may use the pow function in <complex> rather than math.h
Last edited on
Okay, thanks a lot Luc, I'll try that out.
Last edited on
closed account (3hM2Nwbp)
The pow function is a template in <complex>, so you can hand it ints, long ints, or long long ints (*and more).
Last edited on
Topic archived. No new replies allowed.