Answer the question
In order to leave comments, you need to log in
(C++) How to raise an integer to a non-negative integer power?
There is a problem that I can not solve, tell me what I did wrong and how to write it correctly.
Here is the task itself:
Write a power function that implements the raising of an integer to a non-negative integer power. The power function must take two integers as input and return an integer (see code template). When completing the task, please note that the function must be called power, the function must not read anything from the input or output.
Implementation Requirements: In this assignment, you only need to implement the power. You can define helper functions if you need them. You don't need to implement the main functions.
Restrictions: The cmath library (and math.h) is not allowed.
Code template:
int power(int x, unsigned p) {
int answer;
/* count answer */
return answer;
}
Here is my solution:
int power(int x, unsigned p) {
int answer = 1;
for(int i=1; i <= 2 * p; i++)
{ if(p < 0)
break;
answer *= x;
}
return answer;
}
Answer the question
In order to leave comments, you need to log in
int power(int x, size_t p) {
int answer = 1;
for(size_t i = 0; i < p; i++)
answer *= x;
return answer;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question