[英]Finding Average of Array of integers using recursion
I'm trying to find the average of integers elements in an array using recursion .我正在尝试使用recursion查找数组中整数元素的平均值。 I know how to do it using loops, but I have to do it by recursion for my assignment, so what I tried to do is to find the sum of elements using recursion and then divide the sum by the length of the array.
我知道如何使用循环来做到这一点,但我必须通过递归来完成我的任务,所以我试图做的是使用递归找到元素的总和,然后将总和除以数组的长度。 I wrote this code but it gives me a wrong result:
我写了这段代码,但它给了我错误的结果:
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;}
The calling of findAvg method in main class:主类调用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);
}
}
The console output:控制台输出:
Average value of elements = 1
元素的平均值 = 1
First of all sum=a[n-1]+findAvg(a,n-1);
首先
sum=a[n-1]+findAvg(a,n-1);
is wrong, since if findAvg(a,n-1)
returns the correct average for the first (n-1) elements, the sum should be a[n-1] + (n-1) * findAvg(a,n-1)
.是错误的,因为如果
findAvg(a,n-1)
返回前 (n-1) 个元素的正确平均值,则总和应该是a[n-1] + (n-1) * findAvg(a,n-1)
。
Second of all, you are losing precision when dividing integers in avg = sum/n;
其次,在
avg = sum/n;
除整数时会失去精度avg = sum/n;
Consider using doubles.考虑使用双打。
First of all average of integers can be floating point.首先,整数的平均值可以是浮点数。 So make the return type of your function to float or double.
因此,将函数的返回类型设为 float 或 double。 Now,
现在,
If you have set of n
numbers with average of x
and you want to add one more number to the set (say b
).如果您有一组
n
数字,其平均值为x
并且您想在该集合中再添加一个数字(例如b
)。 New average will be ((n * x) + b) / (n + 1).新的平均值将为 ((n * x) + b) / (n + 1)。 Use the same trick in your code.
在您的代码中使用相同的技巧。
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.