Java 如何生成一个接受整数数组并返回平均数的方法?
是的,我不知道如何将总和除以数组中的数字量。问题: 如何生成一个接受整数数组并返回 平均数 回答: 递归地Java 如何生成一个接受整数数组并返回平均数的方法?,java,arrays,eclipse,int,average,Java,Arrays,Eclipse,Int,Average,是的,我不知道如何将总和除以数组中的数字量。问题: 如何生成一个接受整数数组并返回 平均数 回答: 递归地 public static double getAverage(int[] array) { int sum = 0; for(int i : array) sum += i; return ((double) sum)/array.length; } double-getAverage(int[]数组) { return(double)(getSum(array
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ((double) sum)/array.length;
}
double-getAverage(int[]数组)
{
return(double)(getSum(array,0,array.length))/array.length;
}
int getSum(int[]数组、int floor、int cell)
{
如果(ceil-floor<1){抛出新的RuntimeException();}
else if(天花板-地板==1)
{
返回数组[地板];
}
其他的
{
返回getSum(floor,(floor+ceil)/2)+getSum((floor+ceil)/2,ceil);
}
}
要尝试将您引导到正确的方向,您需要尝试将其分解为多个部分。我建议列出完成这项任务需要做的所有事情
- 获取要计算其平均值的值,并将其保存到数组中。
- 这需要知道数据来自何处(文件、键入的文件等)李>
- 它可能还需要知道程序运行时将给出多少值
- 每次遍历数组一个元素,计算所有值的总和。
- 你可以按照Eng.Fouad的例子来做李>
- 得到总和后,只需除以输入到程序中的值的数量即可。这是你的最终平均数
double getAverage ( int [ ] array )
{
return ( double ) ( getSum ( array , 0 , array . length ) ) / array . length ;
}
int getSum ( int [ ] array , int floor , int ceil )
{
if ( ceil - floor < 1 ) { throw new RuntimeException ( ) ; }
else if ( ceil - floor == 1 )
{
return array [ floor ] ;
}
else
{
return getSum ( floor , ( floor + ceil ) / 2 ) + getSum ( ( floor + ceil ) / 2 , ceil ) ;
}
}
从这里开始,您可以开始使用一个函数来计算平均值。请注意,这将截断平均值的小数。例如,2、3和5的“平均值”将是
3
,而不是3.3333..
。在除法之前强制转换为double以避免截断。@Jonathan不能只强制转换为double
,因为函数声明为返回int
@JonathanNewmuis您是对的!然而,当我编译这段代码时,没有任何输出。我做错什么了吗?哪怕是一行字都有错误。你没有试着编译任何东西吗?。。。天哪。没有看到这个答案。
double getAverage ( int [ ] array )
{
return ( double ) ( getSum ( array , 0 , array . length ) ) / array . length ;
}
int getSum ( int [ ] array , int floor , int ceil )
{
if ( ceil - floor < 1 ) { throw new RuntimeException ( ) ; }
else if ( ceil - floor == 1 )
{
return array [ floor ] ;
}
else
{
return getSum ( floor , ( floor + ceil ) / 2 ) + getSum ( ( floor + ceil ) / 2 , ceil ) ;
}
}
Scanner scanner = ... ; # Fill in the '...'
int totalElements = 10; # TODO - Determine what this value should be, or get it from the user
double[] values = new double[totalElements]; # Make an array with totalElements amount of slots
int counter = 0;
while (/* fill this in with scanner method to check for another double*/) {
values[counter] = /* fill in with scanner method to read a double*/;
/* fill in with a way to increase the counter by 1 */
}