所以我试图打印出递归指数方法的实际过程,然后打印出最后的值,但是我的for循环有问题。例如,如果用户输入4到4的功率,它应该打印4到4,4到3,4到2等,然后打印出正确的4到4的功率值,但我继续得到0的值结束。
import java.util.Scanner;
public class Recursion
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter base: ");
int baseNum = input.nextInt();
System.out.println("Enter exponent: ");
int expNum = input.nextInt();
for(int i = 1; i <= baseNum; ++i)
{
System.out.printf("\n%d to the %d", baseNum, expNum--);
}
System.out.printf("\nValue is %d",power(baseNum, expNum));
}
public static int power(int base, int exponent)
{
if(base == 0)
return 1;
else
return exponent * power(base - 1, exponent);
}
}
答案 0 :(得分:4)
您将基数与指数混淆了。功率方法应该像这样定义:
public static int power(int base, int exponent) {
if(exponent == 0) {
System.out.println(1); // for display
return 1;
}
else {
int rem = power(base, exponent-1);
if (rem > 1) {
System.out.println(rem); // for display
}
return base * rem;
}
}
<强> USAGE 强>
public static void main(String[] args) {
System.out.println(power(4,2)); // prints 16
}
答案 1 :(得分:0)
求幂的递归定义是
x^n = x * x^(n-1)
请注意,指数会减少,而不是基数。
答案 2 :(得分:0)
Power = base to exponent。你做错了。正确的方式 -
public static int power(int base, int exponent) {
if(exponent == 0)
return 1;
else
return base * power(base, exponent-1);
}
使上面的代码显示中间结果:
import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter base: ");
int baseNum = input.nextInt();
System.out.println("Enter exponent: ");
int expNum = input.nextInt();
int pow = power(baseNum, expNum);
}
public static int power(int base, int exponent) {
int pow = 0;
if (exponent == 0) {
pow = 1;
System.out.println(base + " raised to " + exponent + " is " + pow);
} else {
pow = base * power(base, exponent - 1);
System.out.println(base + " raised to " + exponent + " is " + pow);
}
return pow;
}
答案 3 :(得分:0)
您的代码存在两个问题
以下是您的代码的编辑版本
import java.util.Scanner;
public class Recursion
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter base: ");
int baseNum = input.nextInt();
System.out.println("Enter exponent: ");
int expNum = input.nextInt();
for (int i = 1; i <= expNum; ++i)
{
System.out.printf("\n%d to the %d", baseNum, i);
}
System.out.printf("\nValue is %d", power(baseNum, expNum));
}
public static int power(int base, int exponent)
{
if (exponent == 0)
{
return 1;
}
else
{
return base * power(base, exponent - 1);
}
}
}