所以我准备好明天的测验,我正在玩数组,我要求用户想要输入多少测试,然后询问测试的每个分数。麻烦我总结测试,它并不总结,请帮助我
import java.util.Scanner;
public class Arrays {
public static void main(String args []){
int numOfElements;
Scanner input = new Scanner(System.in) ;
System.out.println("How many tests are you going to input? ");
numOfElements = input.nextInt();
double array[] = new double [numOfElements];
for (int i=0; i<array.length; i++){
System.out.println("Enter the test # " + (i+1) + ": ");
array[i] = input.nextDouble();
}
for (int i = 0; i<array.length; i++ )
{
System.out.print("Test #"+(i+1)+"= "+array[i] + " pts\n");
}
for (int m= 0; m<array.length; m++)
{ //average value
double sum = 0;
sum = sum + array[m]; //get the sum\
double average = sum / array.length; //get the average value
//print out the sum of elements in an array
System.out.print("Your total points are: "+sum);
//print out the average grade
System.out.println("Your grades is "+average +"%");
}
}
答案 0 :(得分:0)
你的问题在这里:
double sum = 0
在每次循环迭代期间重置你的计数器!
因此,首先,您必须在for循环的前面中移动该声明!同样适用于&#39;普通&#39;!
答案 1 :(得分:0)
你应该在循环中总结得分。 之后,打印结果。
double sum = 0;
for (int m= 0; m<array.length; m++)
{ //average value
sum = sum + array[m]; //get the sum\
}
double average = sum / array.length; //get the average value
//print out the sum of elements in an array
System.out.print("Your total points are: "+sum);
//print out the average grade
System.out.println("Your grades is "+average +"%");
答案 2 :(得分:0)
double sum
和double average
,将它们声明为for循环之外的局部变量,并在迭代完成后打印平均值和求和
double sum = 0;
for (int m = 0; m < array.length; m++) {
sum = sum + array[m];
}
System.out.print("Your total points are: " + sum);
System.out.println("Your grades is " + sum / array.length + "%");
在java8 +中
double array[] = new double[numOfElements];
DoubleSummaryStatistics dss = Arrays.stream(array).summaryStatistics();
System.out.println("average " + dss.getAverage());
System.out.println("sum " + dss.getSum());