如果我输入基数和指数,我设法得到结果,但输出应该是
例如:输出应该如下所示
>>
base:5 exponent:25 ^ 2 = 25
5 ^ 1 = 5
我需要帮助才能在某个地方放置一些东西来实现这一目标......
import java.util.Scanner;
public class recursion {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int base = 0;
int expo = 0;
System.out.print("Enter number for base ");
for (int i = 0; i < 1; i++)
base = scanner.nextInt();
System.out.print("Enter number for exponent ");
for (int j = 0; j < 1; j++)
expo = scanner.nextInt();
System.out.println(base + "^" +expo +" = " + pow(base,expo));
}
public static int pow(int x, int p) {
System.out.println(x + "^" +p +" = " );
if (p == 0)
return 1;
if (p % 2 == 0) {
int a = pow(x, (p / 2));
return a * a; // This line
} else {
int a = pow(x, ((p - 1) / 2));
return x * a * a; // This line
}
}
}
答案 0 :(得分:1)
首先,以下代码段需要审核:
{
for (int i = 0; i < 1; i++)
/*
* This for loop is unnecessary.
* It asserts that the following clause is run only once,
* which is true for any statements anyway.
*/
// ...
}
return a * a;
} /* if (p % 2 == 0) */ else {
/*
* Statements are unnecessarily nested within else clause.
* The corresponding then clause does not complete normally.
* Moving the following code snippet out of an else block
* would have the same effect, but simplifies the control
* statements.
*/
int a = pow(x, ((p - 1) / 2));
return x * a * a;
}
在pow()
方法中,您使用System.out.println()
方法。你正在调用它进行调试,但是当进程正常返回时它是不必要的。当您正在寻找将指数的操作打印为“来自用户指定的指数 - > 1”(“按降序”)时,使用循环打印您的System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));
:
do // New!
System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));
while (expo-- > 1); // New!
} /* main( args ) */
您可以删除pow()
中的调试行。
示例:(>>
表示STDIN)
输入基数
>>
5的数字 输入指数>>
的数字2
5 ^ 2 = 25
5 ^ 1 = 5
输入基数
>>
4的数字 输入指数>>
的数字5
4 ^ 5 = 1024
4 ^ 4 = 256
4 ^ 3 = 64
4 ^ 2 = 16
4 ^ 1 = 4
答案 1 :(得分:0)
void power(int base, int exp){
//Use for loop to iterate through each exp down to 0
for(int i=exp; i>=0; i--){
int result= exponent(base,i);
System.out.println(base + "^" + i + "=" + result)//Will display result as 5^2=25
}
//递归计算b ^ e。
的结果int exponent(int b, int e){
if(e==0){//Base case occurs when e=0.
return (1);
}
return (b * exponent(b,e-1));
}