问题描述
我必须实现一个名为“
的静态公共方法berechneMittelwertWurzel
”。该方法获取一个双精度数组和两个整数值作为输入参数,并返回一个双精度值。 签名:calculateMeanRoot(double[] array,int startindex,int endindex) : double 该方法根据数组中指定范围(startIndex 到 endindex)中的数字计算平均值。根据平均值计算并返回平方根。
忽略两个索引的负值
- 如果 startIndex > endindex 是一个 IntervalException 应该抛出,它继承自 RuntimeExeption。这也应该可以通过消息调用,但应该保留默认构造函数。
- 如果 endindex > array.length -1 或 startIndex
- 如果 double 数组为 null,则返回 0。
- 结果应使用 Math.round() 进行四舍五入。
- 如果计算的平均值小于零 (
有没有更好的方法?
public static double [] berechneMittelwertWurzel(int startindex,int endindex) {
double arr[] = { 5.2,66.23,-4.2,0.0,53.0 };
double sum = 0;
for(int i=0; i<arr.length; i++){
sum = sum + arr[i];
double average = sum / arr.length;
for(int i =0; i < arr.length;i++)
{
for(int j = 0;j < arr.length;j++)
{
if(Math.sqrt(arr[i]) == arr[j])
{
s += arr[j] + "," + arr[i] + " ";
if(index < 0 || index >= array.length)
throw new indexoutofboundsexception();
解决方法
您发布的函数不符合练习中的规范。有各种各样的问题:
- 它的论点是错误的
- 返回类型错误
- 它不会按照指定的方式检查参数或抛出错误
- 您的函数似乎创建了一个字符串(分配给了一个未声明的变量!)对于解决问题来说是不必要的
此外,您的问题标题提到了中位数;但是,您正在尝试计算算术平均值。从问题文本来看,这可能实际上是正确的。请注意,这两个值通常是不同的。
要解决此问题,请从以下签名开始并填补空白:
public static double calculateMeanRoot(double[] array,int startindex,int endindex) {
// if the startIndex > endIndex is an IntervalException should be thrown
// if the endIndex > array.length -1 or startIndex < 0,the IndexOutOfBoundsException shall be thrown
// calculate the sum of the array elements between `startIndex` and `endIndex` (*)
// calculate the mean by dividing the sum by the difference between `endIndex` and `startIndex`
// if the calculated mean is less than zero (<0),then a NegativeNumberException shall be thrown with an output
// calculate the square root of the mean,round it,and return it
}
只有用 (*)
注释的步骤需要循环。