package gradeAvg;
import java.util.Scanner;
//Grade Average calculater
public class GradeAvg {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Please Enter the first grade being added to the average:");
double average = input.nextInt();
System.out.print("The average is now: " + average + " Please enter the second grade being averaged:");
average += input.nextInt() ;
System.out.print("The average is now: " + average + " Please enter the third grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fourth grade being averaged:");
average += input.nextInt() / 2;
System.out.print("The average is now: " + average + " Please enter the fifth grade being averaged:");
average += input.nextInt() / 2;
input.close();
System.out.print(average);
}
}
嘿伙计们,我是java的新手,在数学方面非常糟糕,我应该制作一个允许用户输入值的程序,将其平均化,打印出来,然后允许输入另一个值,进行平均,打印,然后继续。当我在每次输入结束时除以2或者什么时,我会出错?
答案 0 :(得分:1)
平均值是所有数字的总和除以总和中的数字数。
你在这里做的不是平均的。您将每个新数字的一半添加到总和中。我不知道你在这做什么。
为了让事情更容易理解,让我们制作sum
和counter
:
public class GradeAvg {
public static void main(String[] args) {
int sum;
int counter;
// ...
}
}
每当您要求提供号码时,您都会增加计数器并将新号码添加到sum
:
int newNumber;
// ask for input
newNumber = input.nextInt()
sum += newNumber;
counter++;
然后您可以输出这样的平均值:
System.out.println("The average is: " + (double)sum / counter);
答案 1 :(得分:0)
那是错的。你添加的每个数字与其他数字相比增加了50%。 你需要跟踪计数(元素的数量)和总和,每次将总和除以元素的数量。 所以每次添加数字时,函数都应该是:
(OLD_AVERAGE * OLD_COUNT + NEW_NUMBER)/(OLD_COUNT + 1)
或者只使用SUM和COUNT,每次AVERAGE = SUM / COUNT。 INC。每新数字都会计数1。 按输入的数字加总。
答案 2 :(得分:0)
完整的工作解决方案......希望它有所帮助...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int count = 1;
double average = 0;
System.out.print("Please Enter the " + count + " grade being added to the average:");
for (; count <= 5;) {
sum = sum + input.nextInt();
average = sum / count;
System.out.println("The average is now: " + average);
count++;
if (count <= 5)
System.out.println("Please enter the " + count + " grade being averaged:");
}
input.close();
}