gpt4 book ai didi

java - 求平均值、最小值、最大值和范围

转载 作者:行者123 更新时间:2023-12-01 11:36:19 24 4
gpt4 key购买 nike

我是 Java 初学者,我的作业阻止了我编写一段代码来查找输入的平均值、最小值、最大值和范围。这是我的全部代码,尚未完成。平均值很好,但我写的最小值和最大值甚至没有读过。谁能帮我将最小值和最大值连接到我的输入?

package averages;
import java.util.Scanner;

public class Averages {

public static void main(String[] args) {
//initialize variables
double sum =0;
int count = 0;
double grade =0;
//initialize scanner and input
System.out.print("Enter Grades, enter -1 to end the set:");
Scanner in = new Scanner (System.in);
//Process data until sentinel is entered
while (grade != -1)
{
grade = in.nextDouble();
if (grade != -1)
{
sum = sum + grade;
count++;
}
}
// Finding the average
if(count > 0)
{
double average = sum/ count;
System.out.println("Grade Average: "+average);
}
else
{
System.out.println("No Data");
}
//Finding largest grade
double largest = in.nextDouble();
while(in.hasNextDouble())
{
double input = in.nextDouble();
if(input > largest)
{
largest = input;
}
System.out.println(largest);
//Finding smallest grade
double smallest = in.nextDouble();
while (in.hasNextDouble())
{
double input1 = in.nextDouble();
if(input1 < smallest)
{
smallest = input;

}
System.out.println(smallest);
}}}}

最佳答案

public static void main(String args[]) {

//initialize variables
double sum = 0;
int count = 0;
double grade = 0;
double largest = Double.MIN_VALUE;
double smallest = Double.MAX_VALUE;
//initialize scanner and input
System.out.print("Enter Grades, enter -1 to end the set:");
Scanner in = new Scanner(System.in);
//Process data until sentinel is entered
while (grade != -1) {
grade = in.nextDouble();
if (grade != -1) {
sum = sum + grade;
if (grade > largest) {
largest = grade;
}
if (grade < smallest) {
smallest = grade;
}

count++;
}
}
// Finding the average
if (count > 0) {
double average = sum / count;
System.out.println("Grade Average: " + average);
System.out.println("Max Grade: " + largest);
System.out.println("Min Grade: " + smallest);
} else {
System.out.println("No Data");
}
}

关于java - 求平均值、最小值、最大值和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29952290/

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