[英]Power function c++
I have given the code below, I have tried to workout how the function works. 我给出了下面的代码,我尝试了一下该函数的工作方式。 I don't understand what happens when you enter the while loop.
我不明白当您进入while循环时会发生什么。 Does result get multiplied by the power of the value of x?
结果是否乘以x的幂? Why does n get lower?
为什么n会降低? I mainly don't understand what
result *=x;
我主要不明白什么
result *=x;
does. 确实。
//power(x, n) raises integer x to the power n
//no negative powers
int power(int x, unsigned n)
{
int result=1;
while (n>0)
{
result *= x;
--n;
}
return result;
}
Hint, the following lines are equivalent (in this context): 提示,以下几行是等效的(在此上下文中):
result *= x;
result = result * x;
--n;
n = n - 1;
So your function written as simply as possible: 因此,您的函数应尽可能简单地编写为:
int power(int base, int exponent) {
int result = 1;
while (exponent > 0) {
result = result * base;
exponent = exponent - 1;
}
return result;
}
You should have an easier time understanding it now. 您现在应该有一个更轻松的时间来理解它。
The power
function of (x,n)
is just multiply x by n times. (x,n)
的power
函数只是将x乘以n倍。
result *= x;
means result = results * x;
表示
result = results * x;
. 。
while
loop make sure the x
has been multiplied by n
times. while
循环确保将x
乘以n
次。
--n
means n = n - 1
. --n
表示n = n - 1
。 If n=0
, it means x
has been multiplied by n
times. 如果
n=0
,则意味着x
已被乘以n
次。 Then, the loop ends. 然后,循环结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.