Java,比较3个整数,排列最大、中位数和最小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17604892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:27:01  来源:igfitidea点击:

Java, Compare 3 integers, arrange largest, median and smallest

javasortingjvmint

提问by andrsnn

I have been assigned a homework assignment to prompt the user for 3 positive integers then compare and print them in order of largest, median and smallest.

我被分配了一个家庭作业来提示用户输入 3 个正整数,然后按最大、中位数和最小的顺序比较并打印它们。

Prompting and writing a while loop to check if the numbers are positive is fine. I can also figure out how to print the largest and smallest integer.

提示并编写一个 while 循环来检查数字是否为正数是可以的。我还可以弄清楚如何打印最大和最小整数。

(Something like this?)

(类似这样的?)

 if (a >= b) 
       if (a >= c) { max= a; if (b >= c) min= c; else min= b; }
       else { max= c; min= b; }
    else if (b >= c)
       { max= b; if (a >= c) min= c; else min= a; }
    else { max= c; if (a >= b) min= b; else min= a; }

How would I calculate the middle integer using this same schema? I would preferably not use an array yet as the professor has not yet explained them.

我将如何使用相同的模式计算中间整数?我最好不要使用数组,因为教授还没有解释它们。

Any help is appreciated.

任何帮助表示赞赏。

Thank you!

谢谢!

回答by Kon

Store the three numbers in three variables a b c, then use your branching logic to determine the order. You have everything you need to solve this problem here.

将三个数字存储在三个变量中a b c,然后使用您的分支逻辑来确定顺序。您在这里拥有解决此问题所需的一切。

For example

例如

if (a > b && a > c) {
    //Here you determine second biggest, but you know that a is largest
}

if (b > a && b > c) {
    //Here you determine second biggest, but you know that b is largest
}    

if (c > b && c > a) {
    //Here you determine second biggest, but you know that c is largest
}

Inside the comments above is where you would determine the medianand the smallestnumber. The code is wordy, but since you said not to use an array, it's the most straightforward way to understand the problem.

在上面的注释中,您可以确定mediansmallest数字。代码很啰嗦,但既然你说不要使用数组,那么这是理解问题最直接的方法。

回答by Oneeb Sheikh

    int a=2;
    int b=4;
    int c=5;

    if(c>b && c>a){
        system.out.println("c is greater");
    }
    if(b>a && b>c){
        system.out.println("b is greater");
    }
    if(a>c && a>b){
        system.out.println("a is greater");