简体   繁体   English

如何在此代码中获得数组中的最高和最低值?

[英]How to get the highest and lowest value in the array in this code?

I need help to get the highest and lowest value in an array. 我需要帮助以获取数组中的最高和最低值。 I saw some people use Math.max and Math.min but how do you apply it? 我看到有人使用Math.maxMath.min但是您如何应用它呢? in this code? 在这段代码中?

import java.util.Scanner;
public class CaseStudy2A {
    public static void main(String[] args) {
        Scanner inp = new Scanner (System.in);
        int inpNum;
        System.out.print("Enter Number: ");
        inpNum = inp.nextInt();

        int num[]=new int [inpNum];

        int y=0;
        int accu;

            for(int x=0;x<inpNum;x++) {
                y=y+1;

                System.out.print("\nNumber [" + y + "] : ");
                accu = inp.nextInt();

                num[x]=accu;
            }
        for(int x=0;x<inpNum;x++)
        System.out.print(num[x] + " ");
    }
}

If performance is irrelevant you could create a collection from the array and use collection max and min. 如果性能无关紧要,则可以从数组创建一个集合,然后使用集合max和min。

If you want to solve your homework by Math.* you could use this snippet: 如果您想通过Math。*解决作业,可以使用以下代码段:

int max= Integer.MIN_VALUE;
int min= Integer.MAX_VALUE;
for(int x=0;x<inpNum;x++){
 max = Math.max(max,x);
 min = Math.min(min,x);

I get the feeling this is homework... but there's a few ways of doing it. 我觉得这是家庭作业...但是有几种方法可以做到。 You can loop through each element in the array, store the first one you hit into a variable and then check each one after that to see if it's larger than the one currently stored. 您可以遍历数组中的每个元素,将您遇到的第一个元素存储到变量中,然后再检查每个元素以查看其是否大于当前存储的元素。 If it is, overwrite the variable with that one and continue. 如果是,则用该变量覆盖该变量并继续。 At the end you will have the largest one. 最后,您将拥有最大的一个。

Another method would be to sort the array and then take the first and last element in it, giving you the largest and smallest. 另一种方法是对数组进行排序,然后获取数组中的第一个和最后一个元素,从而为您提供最大和最小的元素。

[There was an attempt to edit my post, so I decided to improve it myself] [试图编辑我的帖子,所以我决定自己进行改进]

Introduce 介绍

int min=0, max=0;

then, after the first "for" loop, when all array values are known, do the following: 然后,在第一个“ for”循环之后,当所有数组值都已知时,请执行以下操作:

min=max=num[0];
for(int x=1; x<inpNum; x++) {
  if(num[x]<min) {
    min=num[x];
  }
  else if(num[x]>max) {
    max=num[x];
  }
}

This is faster than calling Math.min/max. 这比调用Math.min / max更快。 Actually, this is the fastest way to compute both minimum and maximum since almost always you end up with less than 2n comparisons (where n is the array length), because when you find a new minimum you don't check for a new maximum. 其实,这是因为几乎总是你最终超过2N比较少(其中n是数组的长度)来计算最小和最大的,因为当你发现一个新的最小你不检查一个新的最大的最快方式。 And that's why the ternary (?:) comparison is not used. 这就是为什么不使用三元(?:)比较的原因。 (You also have to check that inpNum is positive.) (您还必须检查inpNum是否为正。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM