[英]Why is my power function not working properly here?
I've tried changing variable types but this is still not working.我试过改变变量类型,但这仍然不起作用。
double power(double a, long long b){
while(b>1){
a *= a;
b--;
}
return a;
}
Your code won't run properly when b>2 because when you're doing a = a*a;当 b>2 时,您的代码将无法正常运行,因为当您执行 a = a*a; 时the second time it won't be a^3 but a^4 and the next time it will be a^8 and so on.第二次不是 a^3,而是 a^4,下一次是 a^8,以此类推。 The right code would be something like this below:正确的代码如下所示:
double power(double a, long long b){
double k = 1;
while(b>0){
k *= a;
b--;
}
return k;
}
You're changing a
on every iteration.你在每次迭代中都改变a
。 Say you call it like power(2, 3)
.假设您将其称为power(2, 3)
。
First you do 2 * 2
and assign this to a
.首先,您执行2 * 2
并将其分配a
. Next iteration, you'll do again a * a
which is 4 * 4
.下一次迭代,您将再次执行a * a
,即4 * 4
。 Just keep the result in a variable and don't change the arguments:只需将结果保存在变量中,不要更改 arguments:
double power(double a, long long b){
double r = a;
while(b>1){
r *= a;
b--;
}
return r;
}
you are changing the variable a
and it courses the defects.您正在更改变量a
并且它会处理缺陷。 what you can do instead is你可以做的是
double power(double base, double exp)
{
double result = 1;
for(int i = 0; i < exp; i++)
{
result *= base;
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.