Help with code that allows exponential problems.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()

{

    int x;
    int y;

    int result = x^y;

    cout<<"Please enter a number(base): \n";
    cin>>x;

    cout<<"Now enter the exponent please: \n";
    cin>>y;

    cout<<x<<" raised to the power of "<<y<<" is "<<result;

    return 0;

}



Please enter a number(base):            
5                                                                               
Now enter the exponent please:
2                                                                               
5 raised to the power of 2 is 4196208 

I need help correcting this code to display the correct answer.
Last edited on
^ is not exponentiation, it's bitwise XOR. pow() from <cmath> performs exponentiation.
line 11: int result = x^y; x and y are uninitialised. Therefore their values could be equal to anything.

The following result = x^y;, only works once, not for the entire lifespan of the program. If you want result = x^y all the time, you need to make this a function. Or calculate it after you initialise x and y.

Furthermore the XOR operator '^' here isn't doing what you intend (see : http://www.cplusplus.com/doc/boolean/) instead you can use the pow() function (include cmath).

Your possibilities are:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cmath>

using namespace std;

int result(int num, int p) { return (pow(num, p)); }

int main()

{
    int x;
    int y;

    cout << "Please enter a number(base): \n";
    cin >> x;

    cout << "Now enter the exponent please: \n";
    cin >> y;

    cout << x << " raised to the power of " << y << " is " << result(x, y);

    return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cmath>

using namespace std;


int main()

{
    int x;
    int y;
    int result;

    cout << "Please enter a number(base): \n";
    cin >> x;

    cout << "Now enter the exponent please: \n";
    cin >> y;

    result = pow(x, y);

    cout << x << " raised to the power of " << y << " is " << result;

    return 0;
}

Last edited on
Great. Thank you so much.
Topic archived. No new replies allowed.