gpt4 book ai didi

java - 使用迭代计算幂

转载 作者:搜寻专家 更新时间:2023-11-01 01:23:15 24 4
gpt4 key购买 nike

我基本上是在尝试重写 math.pow,我有以下内容,显然我没有得到返回值的概念。我究竟做错了什么?

public static int power(int x, int n)
{
if (n == 0) return 1;
int i,total;
for(i = 0; i < n-1 ;i++);
{
total = (x * total);
}
return total;


}

最佳答案

你需要将total初始化为1。

int total = 1;

您可以将所有内容重写为:

public static int power(int x, int n)
{
int total = 1;
for(int i = 0; i < n; i++) // i can be declared here directly
{
total = (x * total);
}
return total; // total remains 1 if n = 0
}

关于java - 使用迭代计算幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8689343/

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