1

I am trying to calculate the 3rd root of a number.

For example if n=8->2; if n=27->3;

The pow function works well on square root (x^0.5) but it does not work on 3rd root (x^1/3), why is that?

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    int e = 0.3;
    double k;
    cout << "Enter k:" << endl;
    cin >> k;
    k = pow(k, e);
    cout << "The result of k^1/3 " << k << endl;
    return 0;
}
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Isan Rivkin
  • 177
  • 1
  • 15

3 Answers3

5

Two issues:

  • You declare e as an int but try to store a double value in it, so it gets truncated. You need to declare e as double to properly store the value.
  • The value you're using for e is not correct. 0.3 is not the same as 1.0/3.0, so your results will be off. Use 1.0/3.0 for this value instead.
dbush
  • 205,898
  • 23
  • 218
  • 273
2

You've declared the exponent as an integer so it will always be assigned as a zero. declare it as a double.

inside your main try

double e = 1.0/3.0;
double k;
cout << "Enter k:" << endl;
cin >> k;
k = pow(k, e);
cout << "The result of k^1/3 " << k << endl;
return 0;
Euan Smith
  • 2,102
  • 1
  • 16
  • 26
2

You have to use double here:

double e = 1./3.;

instead of int.

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

int main() {
    double e = 1./3.; // <- this line is changed!
    double k;
    cout << "Enter k:" << endl;
    cin >> k;
    k = pow(k, e);
    cout << "The result of k^1/3 " <<k << endl;
    return 0;
}
cwschmidt
  • 1,194
  • 11
  • 17