我在将while循环转换为递归时遇到了问题.循环似乎工作得很好,但是我多次尝试将它转换为递归,方法返回的是最后一个(返回c;)为0.我的意思是,您如何才能将while循环转换为递归呢?程序应该计算数组中低于2的数字。
这是主要的
public static void main(String[] args) {
double[] gpa = new double[]{2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2};
int start = 0;
countGPA(gpa,start);
System.out.println(countGPA(gpa, start));
}这就是方法
public static int countGPA(double[] gpas, int start) {
int L = gpas.length;
int c = 0;
int countGPA = c;
while (start < 10) {
if (start > 0 && start != L) {
if (gpas[start] < 2.0 && gpas[start] > 0) {
c++;
}
} else if (start == L) {
return 0;
} else if (start < 0 && start > L) {
return -1;
}
start++;
}
return c;
}发布于 2020-05-19 19:23:12
这看起来像是一个简单的递归:
public int GPA(double[] gpas, int index){
if(index >= gpas.length) return 0;
if(0 < gpas[index] && gpas[index] < 2) return 1 + GPA(gpas, index + 1);
else return GPA(gpas, index + 1);
}就叫它GPA(gpa, 1)吧。
在你的方法中有很多不必要的比较。看看您对10、L和start的使用。
例如,假设start = 0。您的if中没有人会进入。最好从1开始。看:
if (start > 0 && start != L) //start is 0 so this won't enter
else if (start == L) //start is 0 so this won't enter
else if (start < 0 && start > L) //start is 0 so this won't enter发布于 2020-05-19 19:24:10
递归函数/方法有三件最重要的事情:
这样做如下:
public class Main {
public static void main(String[] args) {
double[] gpa = new double[] { 2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2 };
int start = 0;
System.out.println(countGPA(gpa, start));
}
public static int countGPA(double[] gpas, int start) {
return countGPA(gpas, start, 0);
}
public static int countGPA(double[] gpas, int start, int count) {
if (start >= gpas.length) {// Terminating condition
return count;
}
if (gpas[start] < 2.0 && gpas[start] > 0) {
return countGPA(gpas, ++start, ++count);// The recursive call
} else {
return countGPA(gpas, ++start, count);// The recursive call
}
}
}输出:
4发布于 2020-05-19 19:44:12
创建递归方法时要注意的两件重要事情。
在您的场景中,当索引值等于数组的长度时,递归将停止。
任何可以迭代的内容也可以是递归的候选项。
递归信息:https://www.javatpoint.com/recursion-in-java
public int numbersBelowTwo(double[] gpas, int index){
//Base case, when this statement equates to true
//the recursions stops and returns the values.
if (index == gpas.length) return 0;
return gpas[index] < 2 ? 1 + numbersBelowTwo(gpas, ++ index) : numbersBelowTwo(gpas, ++index);
}https://stackoverflow.com/questions/61898997
复制相似问题