# how to use exponents

This is a discussion on how to use exponents within the C++ Programming forums, part of the General Programming Boards category; what do i use to program exponents in c++ usually its the carrot symbol "^" i tried that and it ...

1. ## how to use exponents

what do i use to program exponents in c++ usually its the carrot symbol "^" i tried that and it doesnt work i was just wondering what that command is in c++

2. there is no command, try using cmath aka math.h.

pow()
i think there is an exp() fxn.

that or you could write your own fxn.

Code:
```#include <iostream>
using namespace std;

namespace MATH
{
template<class type>
type pow(type x, int exp)
{
for(int i = 1; i < exp; i ++, x *= x);
return x;
}
}

int main()
{
cout << MATH::pow(2, 2) << endl;

return 0;
}```

4. yeah I would write my own function too, because the library functions tend to be inefficient ( they are code-heavy because they take into account and handle all sorts of situations that may not even be possible in your situation ).

Code:
```int power( int number , int exponent ){
return ( exponent == 2 ) ? number * number : number * power( number , exponent - 1 );
}```

5. thanks

but for some reason i cant seem to write a function for non "int" numbers i need a function that can handle floating point numbers also such as .5(square root) and like 1.87 anyway any input on this would be very helpfull i just started studying c++ last night

-matt

6. Here's an example of using the one in the library.
Code:
```#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double a;

a = pow(2.,10.);
cout << a << endl;

return 0;
}```

7. When you declare (create) a variable, you have to name the TYPE (char, int, double, float, ect). Look-up "variables" and "types"

Next, look-up how to use cin and cout to input and display numbers in various formats.

In general, when you combine two different types in an equation, the result is "promoted" to the longer/more complex type. If you multiply a float by an int, you get a float. But, you will get an error if you try to assign a float value to an int.

8. Originally posted by DougDbug
But, you will get an error if you try to assign a float value to an int.
you won't get an error, you'll get a warning. the program will still run, the value will just be truncated to become an int.
warning for both initilization and assignment.

9. abrege, your function is erroneous.
Change the function body into this to make it work:
Code:
```type value=x;
for(int i = 1; i < exp; i ++, value *= x);
return value;```

10. Doesn't that have the same effect?

11. Try it!

12. thanks swoopy that did the trick