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>
usingnamespace 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:
#include <iostream>
usingnamespace 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?