gpt4 book ai didi

java - 每次添加东西时尝试取平均值

转载 作者:行者123 更新时间:2023-11-30 07:25:10 25 4
gpt4 key购买 nike

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 时,我会出错吗?

最佳答案

平均值是所有数字的总和除以总和中的数字数量。

你在这里所做的事情并不平均。您将每个新数字的一半添加到总和中。我不明白你在这里做什么。

为了让事情更容易理解,让我们做一个和一个计数器:

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);

关于java - 每次添加东西时尝试取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com