[英]Finding Average of Array of integers using recursion
我正在嘗試使用recursion查找數組中整數元素的平均值。 我知道如何使用循環來做到這一點,但我必須通過遞歸來完成我的任務,所以我試圖做的是使用遞歸找到元素的總和,然后將總和除以數組的長度。 我寫了這段代碼,但它給了我錯誤的結果:
public int findAvg(int a[], int n)
{
int sum,avg;
if(n==1)
{
sum=a[0];
return sum;
}
else
{
sum=a[n-1]+findAvg(a,n-1);
}
avg = sum/n;
return avg;}
主類調用findAvg方法:
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Recursive r = new Recursive ();
int integersArr [] = {1,2,3,4,5};
int max = r.findMax(integersArr,integersArr.length );
int avg = r.findAvg(integersArr, integersArr.length);
System.out.println("Maximum element = "+ max);
System.out.println("Average value of elements = "+ avg);
}
}
控制台輸出:
元素的平均值 = 1
首先sum=a[n-1]+findAvg(a,n-1);
是錯誤的,因為如果findAvg(a,n-1)
返回前 (n-1) 個元素的正確平均值,則總和應該是a[n-1] + (n-1) * findAvg(a,n-1)
。
其次,在avg = sum/n;
除整數時會失去精度avg = sum/n;
考慮使用雙打。
首先,整數的平均值可以是浮點數。 因此,將函數的返回類型設為 float 或 double。 現在,
如果您有一組n
數字,其平均值為x
並且您想在該集合中再添加一個數字(例如b
)。 新的平均值將為 ((n * x) + b) / (n + 1)。 在您的代碼中使用相同的技巧。
public float findAvg(int a[], int n)
{
float sum,avg;
if(n==1)
{
sum=a[0];
}
else
{
// Calculate sum of n-1 numbers = (n-1) * (avg of n-1 numbers)
// and add nth number to it ( i.e. a[n-1])
sum= a[n-1]+ (n-1) * findAvg(a,n-1);
}
avg = sum/n;
return avg;
}
public double average(int y[], int i) {
double result;
result = (double)y[i] / (double)y.length;
if (i == 0)
return result;
else
return result + average(y, i-1);
}
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Recursive r = new Recursive ();
int integersArr [] = {1,2,3,4,5};
int max = r.findMax(integersArr,integersArr.length );
int avg = r.findAvg(integersArr, integersArr.length);
System.out.println("Maximum element = "+ max);
System.out.println("Average value of elements = "+ avg);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.