gpt4 book ai didi

java - 用 Java 计算最小值和最大值?

转载 作者:行者123 更新时间:2023-12-01 09:17:25 27 4
gpt4 key购买 nike

练习的第一部分是计算测试平均分。下一个问题要求我构建这个问题并计算最小值和最大值。谁能帮我?这是我到目前为止的代码。

 import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;

public class hw
{
public static void main ( String[] args )
{
int maxGrade;
int minGrade;
int count=0;
int total=0;
final int SENTINEL = -1;
int score;

Scanner scan = new Scanner( System.in);
System.out.println( "To calculate the class average, enter each test
score.");
System.out.println( "When you are finished, enter a -1.");

System.out.print( "Enter the first test score > ");
score = scan.nextInt();

while (score != SENTINEL )
{
total += score;
count ++;

System.out.print("Enter the next test score > ");
score = scan.nextInt();
}
if (count != 0)
{
DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
System.out.println( "\nThe class average is "
+ oneDecimalPlace.format( (double) (total) / count ));
}
else
System.out.println("\nNo grades were entered");
}

}

最佳答案

while 循环中,您可以将当前分数与最大值和最小值进行比较。

while (score != SENTINEL )
{
total += score;
count ++;
if(score > maxGrade)
maxGrade = score;
if(score < minGrade)
minGrade = score;
System.out.print("Enter the next test score > ");
score = scan.nextInt();
}

您还需要将最大值和最小值(在声明它们时)设置为它们的“相反”值:

int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;

关于java - 用 Java 计算最小值和最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40442858/

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