我是递归新手,有人可以赐教。
问题是:
找到#101的学生测验的平均成绩。"
我已经使用迭代解决了它,但我不知道如何将其转换为递归。
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String arr[][] = {{"101","Quiz","90"},{"101","CS","80"},{"102","Quiz","85"},{"101","Quiz","75"},{"103","CS","84"},{"101","Quiz","87"}};
int sum = 0;
int ave = 0;
System.out.println("Student #\tType\tGrade");
for(int ctr = 0; ctr<arr.length; ctr++){
System.out.println(arr[ctr][0]+"\t\t"+arr[ctr][1]+"\t"+arr[ctr][2]);
if(arr[ctr][0] == "101"){
if(arr[ctr][1] == "Quiz"){
sum += Integer.parseInt(arr[ctr][2]);
ave += 1;
}
}
}
System.out.println("The Average quiz of Student # 101 is: "+ sum/ave);
}
}
答案 0 :(得分:0)
你可以做这样的事情,但我不认为它是优雅/实用/良好的做法:
public int[] recursiveAverage(String array[][], int i){
if (i < array.length)
{
int[] previousAverage = recursiveAverage(array, i + 1);
}
else
{
int[] previousAverage = {0, 0};
}
if (array[i][0] == "101" && array[i][1] == "Quiz")
{
previousAverage[0] = Integer.parseInt(array[i][2]);
++previousAverage[1];
}
return previousAverage;
}
然后您将previousAverage[0]
除以previousAverage[1]
以获得实际平均值。
这实际上是你的迭代函数,用递归代替for
循环。
要有创意。