# Power

• 12-20-2002
sonict
Power
I have this code to find the power of x^y. i already found out how to do x^y but am having trouble doing x^-y (x to the -y power) Here is my code
Code:

```#include <iostream.h> int main() {   double x,y;   double sum = 1;   cout << "Enter the X number : ";   cin >> x;   cout << "Enter the Y number : ";   cin  >> y;   for (int a =1; a<=y; a++)   {       sum = sum * x;   } cout << sum << endl; cin >> hold; }```
Can anyone please give me hints to do x to the -y power?
Thanks.
• 12-20-2002
Polymorphic OOP
rather than multiplying sum by x multiply sum by the inverse of x
• 12-20-2002
sonict
how do i do the inverse of x?
• 12-20-2002
golfinguy4
1/x
• 12-20-2002
sonict
yeah i know its 1/x but how do i do on c++?
• 12-20-2002
sonict
• 12-20-2002
Unless this assignment specifically needs you to perform your own power calculations simply include math.h to your project and use pow(x, y) where it calculates the value of 'x' raised to the 'y' power.

The inverse of a number is the number you can multiply by in order to get 1.

x * (x/x^2) = 1;

EDIT:
1/x is the easier and better way to find the inverse
• 12-20-2002
Polymorphic OOP
Quote:

Originally posted by sonict
yeah i know its 1/x but how do i do on c++?
Why do you think it would be any different?

1.0 / x
• 12-20-2002
ripper079
Quote:

I have this code to find the power of x^y. i already found out how to do x^y but am having trouble doing x^-y (x to the -y power)
Simply do a check if y is greater or less than 0 and use the right method (the one you created or the 1/X method). And if you add a check for y == 0 (easy, returns 1), you will have a complete power function for integral values.
• 12-20-2002
Shiro
>Can anyone please give me hints to do x to the -y power?

Realize that

x^(-y) = 1 / (x^y)