在for循环中查找值的最大值/最小值 [英] Find the Max/Min of values within a for loop

查看:2671
本文介绍了在for循环中查找值的最大值/最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个具体问题的答案,但一直没能找到任何东西。我需要找到输入数字的最大值和最小值,但是我需要的值是在for循环中,我不知道如何使用它们。

  System.out.print(您要输入多少个数字?); 

int totalNumbers = console.nextInt();

int minMax = 0;
for(int i = 1; i <= totalNumbers; i ++){
System.out.print(Number+ i +:);
int inputNumbers = console.nextInt();
}
System.out.println();

int最小= Math.min(minMax);
System.out.println(Smallest =+ smallest);
int maximum = Math.max(minMax);
System.out.println(Largest =+ largest);

我不需要改变代码就可以让我走上正轨。谢谢!

解决方案



<$ p (int i = 1; i <= totalNumbers; i ++){
System.out.print(Number+ i +:); $ p>
int inputNumbers = console.nextInt();



$ b

您正在运行循环 totalNumbers 次,每次创建一个名为 inputNumbers 的新的 int 并存储从控制台接收的值。另外你在哪里改变 minMax 的值?另外 Math.min(或者max)并不需要单个参数,甚至不需要编译。



选项:
$ b


  1. 将所有数字存储在数组中,然后使用某种实用方法遍历最小和最大元素。

  2. 设置一些最小值和最大值并运行一个循环来获取所有项目,并跟踪循环中的最小值和最大值。

我不是在写任何解决方案,因为我希望您自己尝试。

I've searched for answers to this specific question, but haven't been able to find anything. I need to find the maximum and minimum of the input numbers but the values I need are inside the for loop and I can't figure out how to use them outside of it.

System.out.print("How many numbers do you want to input?");

    int totalNumbers = console.nextInt();

    int minMax = 0;
    for(int i = 1; i <= totalNumbers; i++){
        System.out.print("Number " + i + ": ");
        int inputNumbers = console.nextInt();
    }
    System.out.println();

    int smallest = Math.min(minMax);
    System.out.println("Smallest = " + smallest);
    int largest = Math.max(minMax); 
    System.out.println("Largest = " + largest);

I don't need changed code just something that will get me on the right track.Thank you!

解决方案

Can you notice the problem with the following loop?

for(int i = 1; i <= totalNumbers; i++){
        System.out.print("Number " + i + ": ");
        int inputNumbers = console.nextInt();
    }

You are running the loop totalNumbers times and every time you create a new int with name inputNumbers and store the value received from console. Also where are you changing the value of minMax? Also Math.min(or max) does not take single paramtere and wont even compile.

Now you have few options:

  1. Either store all the numbers in an array and then traverse that for min and max elements using some utility method.
  2. Set some min and max value and run a loop to get all items and also keep track of min and max in loop.

I am not writing any solution as I want you to try it yourself.

这篇关于在for循环中查找值的最大值/最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆