仅使用递增、递减、循环和 =0 来制作 pow(x1, x2) 函数
Making a pow(x1, x2) function using only increments, decrements, loops, and =0
这些是我的问题的限制——我正在尝试使用另一种计算方法来解决这个问题,但首先尝试在 Java 中解决它。我可以阅读其他语言。
这是我目前拥有的:
public static int pow(int x1, int x2){
if(x1 == 0) return 0;
if(x2 == 0) return 1;
int exp = x2;
int y = x1;
exp--;
int multi = x1;
while(exp != 0) {
int temp = y;
while(multi !=0) {
while (temp != 0) {
y++;
temp--;
}
multi--;
}
exp --;
multi = x1;
System.out.println();
}
return y;
}
pow(4,4)
应该是 256
,但我得到 32
。 pow(5,4)
应该是 625
,但我得到 40
。
我试图尽可能少地更改您的实现以获得正确的结果(因为它几乎是正确的!)。
本质上,您需要在内部 while 循环中重复使用您分配给 temp 的 y 值。为此,我添加了变量 loopTempY。
另一个小改动是外部循环,你只需要循环到大于 1 即可。
public static int pow(int x1, int x2) {
if (x1 == 0) return 0;
if (x2 == 0) return 1;
int exp = x2;
int y = x1;
int multi;
while (exp > 1) {
multi = x1;
int temp = y;
int loopTempY = temp;
while (multi != 1) {
while (temp != 0) {
y++;
temp--;
}
temp = loopTempY;
multi--;
}
exp--;
System.out.println(y);
}
return y;
}
这些是我的问题的限制——我正在尝试使用另一种计算方法来解决这个问题,但首先尝试在 Java 中解决它。我可以阅读其他语言。
这是我目前拥有的:
public static int pow(int x1, int x2){
if(x1 == 0) return 0;
if(x2 == 0) return 1;
int exp = x2;
int y = x1;
exp--;
int multi = x1;
while(exp != 0) {
int temp = y;
while(multi !=0) {
while (temp != 0) {
y++;
temp--;
}
multi--;
}
exp --;
multi = x1;
System.out.println();
}
return y;
}
pow(4,4)
应该是 256
,但我得到 32
。 pow(5,4)
应该是 625
,但我得到 40
。
我试图尽可能少地更改您的实现以获得正确的结果(因为它几乎是正确的!)。
本质上,您需要在内部 while 循环中重复使用您分配给 temp 的 y 值。为此,我添加了变量 loopTempY。
另一个小改动是外部循环,你只需要循环到大于 1 即可。
public static int pow(int x1, int x2) {
if (x1 == 0) return 0;
if (x2 == 0) return 1;
int exp = x2;
int y = x1;
int multi;
while (exp > 1) {
multi = x1;
int temp = y;
int loopTempY = temp;
while (multi != 1) {
while (temp != 0) {
y++;
temp--;
}
temp = loopTempY;
multi--;
}
exp--;
System.out.println(y);
}
return y;
}