[英]Take the average of elements in array
So I'm getting ready for a quiz tomorrow and I was playing around with arrays, I'm asking for how many tests the user wants to input then ask for every score of a test. 因此,我明天准备进行测验,并且正在使用数组,要求用户要输入多少个测试,然后要求每个测试得分。 the trouble im having is summing up the tests, it doesn't sum all up, please help me
我遇到的麻烦是对测试进行汇总,而不能汇总全部,请帮助我
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 +"%");
}
}
Your problem is here: 您的问题在这里:
double sum = 0
That resets your counter during each loop iteration! 这会在每次循环迭代期间重置您的计数器!
So, for starters, you have to move that statement in front of your for loop! 因此,对于初学者来说,您必须将该语句移到for循环的前面 ! Same for 'average'!
“平均”也一样!
You should sum up the scores in the loop. 您应该在循环中总结分数。 After that , you print the results.
之后 ,您将打印结果。
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 +"%");
double sum
and double average
are reset every iteration, declare them as local variables outside the for-loop, and print average and sum once the iteration is completed 每次迭代都会重置
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 + "%");
In java8+ 在Java8 +中
double array[] = new double[numOfElements];
DoubleSummaryStatistics dss = Arrays.stream(array).summaryStatistics();
System.out.println("average " + dss.getAverage());
System.out.println("sum " + dss.getSum());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.