将while循环转换为递归

时间:2020-05-19 19:16:10

标签: java loops recursion

我在将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;
}

3 个答案:

答案 0 :(得分:1)

这看起来像一个简单的递归:

module Cswk2 where

getCard :: Integer -> [Integer]
getCard n
      | n < 0 = []
      | otherwise = lst_numb : getCard pre_numb
       where
         (pre_numb, lst_numb) = n divMod 10

只需将其命名为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)10L的使用。


例如,假设start。您的start = 0中没有人会进入。最好从1.开始。

if

答案 1 :(得分:0)

关于递归函数/方法,最重要的三件事:

  1. 终止条件。
  2. 以递归方式调用方法/函数的值。
  3. 在何处(在递归调用之前/之后)处理参数。

执行以下操作:

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

答案 2 :(得分:0)

创建递归方法时要注意的两件事。

  1. 您必须包含一个基本情况,当为true时,它将停止递归调用并返回值。如果没有基本情况,则会遇到StackOverFlow异常。

在您的方案中,当索引值等于数组的长度时,递归将停止。

  1. 该方法必须从内部调用自身。

任何可以迭代的内容也可以作为递归的候选对象。

有关递归的信息: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);

}
相关问题