cmath pow

Hi. It's been couple of days since I'm learning c++. Me and my friend challenged each other to write a program which calculates a certain root of a number. I tried with a small step: to calculate the floor of the number. I came up with this codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
  long num;
  int wroot;
  int i=0;
  cin >> num >> wroot;

while(pow(i,wroot) < num){i++;}
if (pow(i, wroot) != num){i--;}

  cout << i;
}


This code "must" totally work. But it doesn't. It returns wrong number(e.g. 4 instead of five, 2 instead of 3). I fail to see any flaw. What's baffling: when I personally write a function for raising to a power and call it, it works! Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

int pow(int x, int y)
{
    int i=0;
    int result=1;

    while (i<y)
    {
        result *= x;
        i++ ;
    }
    return result;
}

int main()
{

  long num;
  int wroot;
  int i=0;
  cin >> num >> wroot;

while(pow(i,wroot) < num){i++;}
if (pow(i, wroot) != num){i--;}

  cout << i;

}


What's wrong with it? Do I misuse the cmath pow function or what?
Last edited on
It's problematic to compare with floating point numbers.

See: 4.000000001 != 4

You need to define the numbers of decimal places which are relevant.
Topic archived. No new replies allowed.