我想将我从2D数组中获得的平均值存储到1D数组中。我不确定该怎么做!
package javaprogram;
import java.util.Scanner;
public class program {
public static void main(String[] args) {
//a one-dimensional array to store the student names
String names[] = {"Johnson","Aniston","Cooper","Gupta",
"Blair","Clark","Kennedy","Bronson","Sunny", "smith"};
// a 2 dimentional array to store scores
int[][] scores = { {85, 83, 77, 91,76}, {80,90,95,93,48},
{78,81,11,90,73},{92,83,30,69,87}, {23,45,96,38,59}, {60,85,45,39,67},
{77,31,52,74,83}, {93,94,89,77,97},{79,85,28,93,82},{85,72,49,75,63}};
//a 1 dimentional array to store grades
double[] grade = new double[10];
double sum=0, average=0;
for(int row=0; row<10; row++)
{
sum = 0;
for(int col=0; col<scores[row].length; col++)
{
sum = sum +scores[row][col];
average= sum/5;
}
System.out.println(average);
}
}
}
答案 0 :(得分:3)
像这样吗?
time.sleep(n)
答案 1 :(得分:1)
进行此修改
double[] grade = new double[10];
double sum=0, average=0;
for(int row=0; row<10; row++) {
sum = 0;
for(int col=0; col<scores[row].length; col++){
sum += scores[row][col];
}
average = sum/5;
grade[row] = average;
}
average= sum/5;
grade[row] = sum/5;
请注意,由于您的所有分数均为 for(int row=0; row<10; row++)
{
sum = 0;
for(int col=0; col<scores[row].length; col++)
{
sum = sum +scores[row][col];
}
grade[row] = sum/5; // store it in your array each rows average
System.out.println(grade[row]);
}
,因此您将获得整数平均值而不是十进制平均值。