我将在下面发布我的代码,因为这有点难以描述。下面的代码有效,但它在 main 方法中而不是在 helper 中使用 Math.pow,所以如果有人能告诉我一种方法将权力转移到 helper 方法而不弄乱程序,我将不胜感激。
主要方法:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
辅助方法:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
编辑:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
最佳答案
像这样的东西会起作用。你根本不需要使用幂函数。只需从 1 星开始,然后在递归的每一步中将星数加倍。
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
关于java - 在递归方法中有一个变量在每次调用后都不会重新定义自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287626/