簡體   English   中英

使用遞歸取數組的平均值

[英]Take Average of an Array using Recursion

我正在嘗試創建一個程序,該程序將接受用戶輸入,將該數據輸入到動態數組中,然后遞歸地找到平均值。 我的代碼的第一部分有效。 這允許將新創建的數組傳遞給該方法。

 public static void main(String args[])
{
    
    int i = 0;
    int sum = 0;
    double runningTotal = 0;
    
    int classSize;
    Scanner keyboard = new Scanner(System.in);      
    System.out.println("Please enter the class size: ");
    classSize = keyboard.nextInt();
    int newClassSize[] = new int[classSize];
    
    for (i=0; i < newClassSize.length; i++)
    {
        System.out.println("Please enter the grade of the user at: " + (i + 1));
        newClassSize[i] = keyboard.nextInt();   
    }
    
    findAverage();
    
    
    for (i=0; i < newClassSize.length; i++){
                
        
        sum = sum + newClassSize[i];
    }
                    
    System.out.println(Arrays.toString(newClassSize));
            
    
keyboard.close();
    
}
}

然而,這就是我感到困惑和困惑的地方。 如何將新創建的數組傳遞給 findAverage() 方法? 然后,我還需要將其保存到累加器中,然后除以。 有一個更好的方法嗎? 這是我當前的 findAverage() 方法,但我對自己的實現感到困惑。

public double findAverage(int classAverage, int baseCase, double runningAverage)
{
    runningAverage = 0;
    int sum = 0;
    
    if (newClassSize.length - 1 > baseCase)
        runningAverage = newClassSize.length;
        
    
    return findAverage();
    System.out.println("The class average is " + classAverage);
    
}
    

希望我正確理解了您的問題,但下面是如何做到這一點。 基本思想是,當索引達到遞歸 function 中的數組長度時,這是基本情況。 因此,您所要做的就是將數組中每個索引點的總和相加,然后繼續將更新后的索引和總和傳遞到遞歸 function 中。

class Main {
    public static void main(String[] args) {
        int newClassSize[] = {1,2,3}; // User Input let say

        
        double average = findAverage(newClassSize);
        System.out.println(average);
    }
    
    
    public static  double findAverage(int[] arr){
        // Avoid division by zero error
        if (arr.length==0){
           return 0;
        }
        return findAverageHelper(arr,0,0);
    }
    
    
    public static  double findAverageHelper(int[] arr, int index,int sum){
        if (index==arr.length){ // Base Case 
            return (double) sum/arr.length;
        }
        // Increase index and add current value at index to sum
        return findAverageHelper(arr,index+1,sum+=arr[index]);
        
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM