gpt4 book ai didi

c++ - 幂函数c++

转载 作者:行者123 更新时间:2023-11-27 22:55:19 25 4
gpt4 key购买 nike

我已经给出了下面的代码,我已经尝试过这个函数是如何工作的。我不明白当你进入 while 循环时会发生什么。结果是否乘以 x 值的幂?为什么 n 变低了?我主要是不明白result *=x; 是做什么的。

//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;
}

最佳答案

提示,以下几行是等效的(在此上下文中):

result *= x;
result = result * x;

--n;
n = n - 1;

所以你的函数写得越简单越好:

int power(int base, int exponent) {
int result = 1;
while (exponent > 0) {
result = result * base;
exponent = exponent - 1;
}
return result;
}

你现在应该更容易理解它了。

关于c++ - 幂函数c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33715594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com