我有这样的家庭作业问题:
以下数据代表地震的里氏震级数据。编写一个程序来计算和打印任何有效地震数据的平均值。
将 Richter 值存储在名为 quakeLevels 的双精度数组中。
不幸的是,众所周知,您的地震仪有时会产生不可靠的读数(例如本例中的值 10.1)。所以你决定扔掉最大和最小读数。
您的程序应该执行以下操作:
使用以下数据声明并初始化 quakeLevels 数组。 { 5.6, 6.2, 4.0, 5.5, 5.7, 6.1,7.4, 8.5, 5.5, 6.3, 6.4, 2.1, 6.9, 4.3, 3.1, 7.0, 10.1 }
确定数组中的最大值和最小值。计算数组内容的平均值,不包括最大值和最小值。打印数组中不包括最大值和最小值的值。打印平均值。
我不能使用数学类,所以这就是为什么所有的东西都被写出来打印最大值和最小值。
到目前为止,这是我的代码:
public class ARRAYminAndmax0RichterScale
{
public static void main(String [] args)
{
double [] quakeLevels = { 5.6, 6.2, 4.0, 5.5, 5.7, 6.1 ,7.4, 8.5, 5.5, 6.3, 6.4, 2.1, 6.9, 4.3, 3.1, 7.0, 10.1};
double [] quakeLevelsNormalized = new double [(quakeLevels.length - 2)];
int i;
int minIndex = 0; // start with 0th element as min
for ( i = 1; i < quakeLevels.length; i++) {
if (quakeLevels[i] < quakeLevels[minIndex]) {
minIndex = i;
}
}
System.out.print("Min: " + quakeLevels[minIndex] + " ");
int maxIndex = 0; // start with 0th element as max
for ( i = 1; i < quakeLevels.length; i++) {
if (quakeLevels[i] > quakeLevels[maxIndex]) {
maxIndex = i;
}
}
System.out.println("Max: " + quakeLevels[maxIndex]);
System.out.println("The Richter values, excluding the extrema, are as follows: ");
//make a new array excluding the max and min
for ( i = 1; i < quakeLevels.length - 2; i++ ) {
if(quakeLevels[i]!= minIndex && quakeLevels[i]!= maxIndex){
quakeLevelsNormalized[i] = quakeLevels[i];
System.out.printf("%6s\n", quakeLevelsNormalized[i] );
}
}
//***THIS LOOP IS HERE TO HELP ME FIGURE OUT THE PROBLEM***
for( i =0; i < quakeLevelsNormalized.length; i++){
System.out.println("quakeLevelsNormalized["+i+"] = " + quakeLevelsNormalized[i]);
}
//find average of quakeLevelsNormalized
double arrayTotal = 0;
double average = 0;
for (i = 0; i < quakeLevelsNormalized.length; i++) {
arrayTotal = arrayTotal + quakeLevelsNormalized[ i ];
}
average = arrayTotal / quakeLevelsNormalized.length;
//output
System.out.println( quakeLevelsNormalized[i-1]);
System.out.printf("%s%.1f\n","Average Quake Level = ", average);
}
}
我得到以下输出:
Min: 2.1 Max: 10.1
The Richter values, excluding the extrema, are as follows:
6.2
4.0
5.5
5.7
6.1
7.4
8.5
5.5
6.3
6.4
2.1
6.9
4.3
3.1
quakeLevelsNormalized[0] = 0.0
quakeLevelsNormalized[1] = 6.2
quakeLevelsNormalized[2] = 4.0
quakeLevelsNormalized[3] = 5.5
quakeLevelsNormalized[4] = 5.7
quakeLevelsNormalized[5] = 6.1
quakeLevelsNormalized[6] = 7.4
quakeLevelsNormalized[7] = 8.5
quakeLevelsNormalized[8] = 5.5
quakeLevelsNormalized[9] = 6.3
quakeLevelsNormalized[10] = 6.4
quakeLevelsNormalized[11] = 2.1
quakeLevelsNormalized[12] = 6.9
quakeLevelsNormalized[13] = 4.3
quakeLevelsNormalized[14] = 3.1
3.1
Average Quake Level = 5.2
问题
所以这显然不是它应该的样子。为什么它最后会给我额外的 3.1?它只有 14 个元素,什么时候应该有 [18 减去两个极端]?我是一个初学者程序员 - 我非常感谢任何和所有的帮助!