^x

Hi,

I'm following absolute beginner tutorials c++. Now, in the first exercise, there is asked to let the user input a number (variable "number" for example) and compute it number^3. Not that it's hard, just number * number * number. But what if you don't know the 3? Is there a better way so you can easly do ^x?

Thanks :)
<cmath> provides the 'pow' function:

1
2
3
4
#include <cmath>

//...
number = std::pow(base,exponent);


Or you could do a for loop:

1
2
3
number = base;
for(i = 1; i < exponent; ++i)
  number *= base;


pow has the benefit of working with non-integer types, as well as negative exponents.

Also to avoid possible confusion later.. the ^ operator in C/C++ performs a xor operation -- not an exponent.
Hey,

Thank you very much for the reply; I'll check it out :)
Hmmm, that doesn't seems to work for some reason.

This is the code I have:

1
2
3
4
5
6
7
8
9
10
#include <iostream> 
#include <cmath>

using namespace std;

int main()
{
double x = pow(5,3);
cout << x << endl;
}


I'm getting this as error:
1>c:\users\bjorn\documents\visual studio 2008\projects\basis1\basis1\test1.cpp(8) : error C2668: 'pow' : ambiguous call to overloaded function
1> d:\program files\microsoft visual studio 9.0\vc\include\math.h(575): could be 'long double pow(long double,int)'
1> d:\program files\microsoft visual studio 9.0\vc\include\math.h(527): or 'float pow(float,int)'
1> d:\program files\microsoft visual studio 9.0\vc\include\math.h(489): or 'double pow(double,int)'
1> while trying to match the argument list '(int, int)'


What am I doing wrong?
double x = pow(5.0,3.0);

There are several different kinds of 'pow' functions. One takes floats, one takes doubles, and one takes long doubles. The compiler needs to know which one to use based on the parameters you pass. Since passing an integer is ambiguous, it yells at you because it doesn't know which version to use.

Putting in the .0 (5.0 instead of 5) declares the number as a type 'double' which tells the compiler to use the double version. Another way to do this would be to cast:

double x = pow( double(5), double(3) );
Hi Disch

Thank you very much for the explaination - it works fine now! :)
it will be better for you if you try to write the function yourself and not use the standard library function.
just a suggestion.
Topic archived. No new replies allowed.