我正在尝试使用 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
答案 0 :(得分:2)
首先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;
中分割整数时,你正在失去精度。考虑使用双精度。
答案 1 :(得分:1)
首先,整数的平均值可以是浮点数。因此,使函数的返回类型为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;
}
答案 2 :(得分:1)
{
"name": "mytestapplication",
"version": "0.0.0",
"dependencies": {
"angular": "^1.4.0",
"bootstrap": "^3.2.0",
"angular-ui-router": "^0.3.1",
"animate.css": "^3.5.2",
"angular-animate": "^1.5.8",
"satellizer": "^0.15.4",
"moment": "^2.14.1"
},
"devDependencies": {
"angular-mocks": "^1.4.0"
},
"appPath": "app",
"moduleName": "test2App",
"overrides": {
"bootstrap": {
"main": [
"less/bootstrap.less",
"dist/css/bootstrap.css",
"dist/js/bootstrap.js"
]
}
},
"homepage": "https://github.com/myusername/myapp",
"description": "my application",
"main": "app/index.html",
"license": "MIT",
"private": true,
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
答案 3 :(得分:0)
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);
}
}