找到更大和更低的数字

我需要编写一个程序,该程序将从用户 5 号 (abcde) 获取并打印最低和最高数字。我该怎么做并使用更少的 if-elss 条件?我不能使用 arry 或循环。


    if (a>b) {

        min=b ;

        max=a ;

    }else {

        min=a ;

        max=b ;

        int temp = a ;

        a=b ;

        b=temp ;

    }

    if (b>c) {

        min=c ; 

    }else {

        if(c>max) {

            max=c ;}

        int temp = b ;

        b=c ;

        c=temp ;

    }

    if (c>d) {

        min=d ;

    }else {

        if(d>max) {

            max=d ;}

        int temp = c ;

        c=d ;

        d=temp ;

    }

    if (d>e) {

        min=e ;


    }else {

        if(e>max) {

            max=e ;}

        int temp = d ;

        d=e ;

        e=temp ;}


慕桂英4014372
浏览 200回答 3
3回答

翻阅古今

一种选择是将五个输入数字添加到一个数组中,然后使用流来查找最小值和最大值:int a = myScanner.nextInt();int b = myScanner.nextInt();int c = myScanner.nextInt();int d = myScanner.nextInt();int e = myScanner.nextInt();int[] vals = {a, b, c, d, e};int min = Arrays.stream(vals).min().getAsInt();int max = Arrays.stream(vals).max().getAsInt();System.out.println(min);System.out.println(max);另一种选择可能是使用集合(例如列表)来存储五个输入数字。然后,我们可以对该集合进行排序,并以这种方式找到最小值/最大值。使用某种集合可能是最好的方法。编辑:如果您必须使用if语句,那么一种选择可能是成对比较前两个和后两个数字,然后从结果三个数字中找到最小值/最大值。我改编了这个代码审查问题中的min和max方法。它找到三个数字的最小值和最大值,所以我们只需要提出额外的逻辑来将你的五个输入减少到三个。public static int min(int a, int b, int c) {&nbsp; &nbsp; if (a <= b && a <= c) return a;&nbsp; &nbsp; if (b <= a && b <= c) return b;&nbsp; &nbsp; return c;}public static int max(int a, int b, int c) {&nbsp; &nbsp; if (a >= b && a >= c) return a;&nbsp; &nbsp; if (b >= a && b >= c) return b;&nbsp; &nbsp; return c;}// now the logic for your inputs a, b, c, d, eint min1 = a <= b ? a : b;int min2 = c <= d ? c : d;int max1 = a >= b ? a : b;int max2 = c >= d ? c : d;int finalmin = min(min1, min2, e);int finalmax = max(max1, max2, e);

呼唤远方

你需要做的是在相反的极端初始化最小值和最大值,并定义一个变量来保存最新的输入;int max=Integer.MIN_VALUE;int min=Integer.MAX_VALUE;int input;然后,您输入并检查输入是新的min还是max:input = myScanner.nextInt() ;if(input<min){...}if(input>max){...}然后,您只需根据需要将其复制粘贴多次以获取输入(通常您会使用 for 循环,但无论如何)。

犯罪嫌疑人X

我认为流就像使用循环,所以简单点:int min = a;int max = a;if (max < b) {max = b;}&nbsp;if (min > b) {min = b;}&nbsp;if (max < c) {max = c;}&nbsp;if (min > c) {min = c;}&nbsp;...System.out.println(min);System.out.println(max);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java