Exponents in C++ by using loops
Solution 1
Take a look at this loop:
for (int i=0; i<=x; i++)
a= a*a;
cout << "The answer is: " << a;
}
Every time you go through this loop, you multiply a by itself. Let's suppose the user enters number a0. Then:
- After 0 iterations, a has value a0.
- After 1 iteration, a has value a02
- After 2 iterations, a has value a04
- After 3 iterations, a has value a08
- ...
For example, if a = 2 and x = 4, the values will be 2, 4, 16, and 256, which are way bigger than you want them to be.
To fix this, try changing your loop so that you have a secondary variable, initially set to 1, that you keep multiplying by a. That way, you don't change what value you're multiplying by on each iteration.
Next, note that your loop is running too many times. Since you loop up to and including x, your loop runs x + 1 times, so if you want to compute ax you will get the wrong value. Try changing this to loop exactly x times.
Finally, your print statement runs on each iteration, so you'll see all the intermediary values. Change the code so that the print statement is outside the loop.
After doing all that, do look up the pow
function. If this is for an assignment you might not be able to use this function, but it's the easiest way to solve this problem.
Hope this helps!
Solution 2
There are a couple of errors:
for (int i=0; i<=x; i++)
this will loop for x+1
times, not what you intended.
a= a*a;
every time you do this, a
is the value that is already multiplied, so you need another variable to store the result.
int result = 1;
for (int i=0; i<x; i++)
result *= a;
}
cout << "The answer is: " << result;
One last note, to calculate a^x
, int
may be too small for many practical cases, consider a bigger type like long long
.
Solution 3
int result = 1;
for (int i=1; i<=x; i++)
{
result= result*a;
}
cout << "The answer is: " << result;
}
Hope This will work for you
Admin
Updated on June 05, 2022Comments
-
Admin almost 2 years
I need some help. I want to compute ax given real value a and positive value integer x.
My program:
#include <iostream> using namespace std; int main() { int a, x; cout << "Input a: "; cin >> a; cout << "Input x: "; cin >> x; for (int i=0; i<=x; i++) a= a*a; cout << "The answer is: " << a; }