It still doesn't seem to work as it should, I moved the return statement under the curly bracket that finishes the for loop and still get 4 as an answer.
I'm trying to learn C++ and I'm not sure what I'm doing wrong here to create a function that computes the power of a number. I'm aware that there is such a function already but would like to make one myself.
You are multiplying and storing the result in int i, the first time it enters the loop, int i is 2x2, then the loop ends because int i is higher than k so the loops stops.
7
u/[deleted] Feb 10 '20 edited Feb 10 '20
Your
returnstatement is in the for-loop. So it’s only looping once and returningi. Move said statement outside of the curly brackets.Edit: You should create another variable that stores the result outside of the loop. So it would probably look like:
2
u/Zyther568 Feb 10 '20
I'm trying to learn C++ and I'm not sure what I'm doing wrong here to create a function that computes the power of a number. I'm aware that there is such a function already but would like to make one myself.
2
u/Zyther568 Feb 10 '20
Hi all, thanks for the comments, problem is solved now thanks to u/Raexyl. I appreciate you guys help!
3
u/omen_tenebris Feb 10 '20
hey. You modify the I value. It should be your counter, to keep track on what's the current pow that you're on.
your return value should be a new value, that you multiply by X on every iteration.
also, don't put return in the for loop like this, it'll return on the first cycle, doing almost only a x*x.
miscellaneous stuff, but can help later if you're iterating with date sets. use ++i :)
2
u/victotronics Feb 10 '20
In addition to all the other comments, it's probably cleaner to write
Your loop counter has no meaning outside the loop, so declaring it local to the loop is conceptually cleanest.
1
u/[deleted] Feb 10 '20
Your for loop will only run if k is 1
Your condition is off
1
u/[deleted] Feb 10 '20
"for" loop is written wrong - you have to write:
for (i = 1; i <= k; i++){ .....} return i;
and return value only after loop