在Java中计算最小值和最大值?

摩尔

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

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

     }
ItamarG3

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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在for循环中计算最大值-最小值

最小值和最大值

Java-寻找有关在步长间隔中计算函数或导数的最小值/最大值的建议

检测局部最小值和最大值,Java

数组中的Java最小值和最大值

输入数组java的最小值和最大值?

对两列求和,在 MapReduce 中计算最大值、最小值和平均值

如何在postgresql中计算最大值,最小值和平均值

找出直方图中计数最多的最大值和最小值

如何从输入中计算出一系列计算的平均值和最大值/最小值?

在计算平均值的同时使用groupby计算最小值和最大值

计算最大值和最小值Javascript时得到错误的值

从 C 中的终端计算最小值/最大值

输入值的最小值和最大值

Python数据帧计算元素列表的最小值和最大值

计算数据框中列的最大值、平均值和最小值

使用 apply 计算向量列表的最大值和最小值

优雅地同时计算数字数组的最小值和最大值

用熊猫首次出现的索引计算过渡的最小值和最大值

计算总和,平均值,最大值和最小值

使用dplyr分组时如何计算均值,最小值和最大值?

Python中的列表推导,可计算列表的最小值和最大值

有条件地计算列的最大值和最小值

从SpatialLinesDataFrame对象计算出的坐标的最小值和最大值

如何使用 awk 计算多列(按行)的最大值和最小值

计算不同表中最大值和最小值之间的差异

根据水年计算平均值、最大值和最小值

计算MySQL8中重复条目组的最大值和最小值之和

如何计算每个唯一条目的最大值和最小值