在java中怎么比较三个整数大小例如(a , b, c);并从小到大输出

2020-04-24 教育 89阅读

package work;

import java.util.Scanner;//导包,获取键盘输入

public class Demo01 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("输入数字a");

int a = sc.nextInt();

System.out.println("输入数字b");

int b = sc.nextInt();

System.out.println("输入数字c");

int c = sc.nextInt();

if (c < a && c < b && b < a) {// 通过比较c

System.out.println("一号a:" + a+"\n二号b:" + b+"\n三号c:" + c);

} else if (c < a && b < c && b < a) {

System.out.println("一号a:" + a+"\n二号c:" + c+"\n三号b:" + b);

} else if (c < a && c < b && a < b) {

System.out.println("一号b:" + b+"\n二号a:" + a+"\n三号c:" + c);

} else if (a < c && a < b && c < b) {

System.out.println("一号b:" + b+"\n二号c:" + c+"\n三号a:" + a);

} else if (a < b && a < c && b < c) {

System.out.println("一号c:" + c+"\n二号b:" + b+"\n三号a:" + a);

} else if (b < a && b < c && a < c) {

System.out.println("一号c:" + c+"\n二号a:" + a+"\n三号b:" + b);

}

}

}

解题思路:

可以用if else if语句判断,通过else if多次判断来输出。

假设C

if (c < a && c < b && b < a){

System.out.println("老大" + a,"老二"+b+"老三"+c);

} else if(比较条件){ }

按这个思路一一判断过去,得出A B C 三个值的大小。

扩展资料

java中三个整数排列的其他解法

import java.util.Scanner;

public class lianxi34 {

public static void main(String[] args) {

Scanner s = new Scanner(System.in);

System.out.println("输入3个整数:");

int a = s.nextInt();

int b = s.nextInt();

int c = s.nextInt();

if(a < b) {

int  t = a;

a = b;

b = t;

}

if(a < c) {

int t = a;

a = c;

c = t;

}

if(b < c) {

int t = b;

b = c;

c = t;

}

System.out.println("从大到小的顺序输出:");

System.out.println(a + " " + b + " " + c);}}

声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com