網頁

工商專區

2013年12月26日

三數比大小

輸入三個數,將三個由大到小做排序


  1. import java.util.Scanner;
  2.  
  3. public class Demo {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8.  
  9. int a = sc.nextInt();
  10. int b = sc.nextInt();
  11. int c = sc.nextInt();
  12.  
  13. System.out.println();
  14.  
  15. if (a >= b) {
  16. if (b >= c) {
  17. System.out.printf("%d >= %d >= %d", a, b, c);
  18. } else if (a >= c) {
  19. System.out.printf("%d >= %d >= %d", a, c, b);
  20. } else {
  21. System.out.printf("%d >= %d >= %d", c, a, b);
  22. }
  23. } else {
  24. if (a >= c) {
  25. System.out.printf("%d >= %d >= %d", b, a, c);
  26. } else if (b >= c) {
  27. System.out.printf("%d >= %d >= %d", b, c, a);
  28. } else {
  29. System.out.printf("%d >= %d >= %d", c, b, a);
  30. }
  31. }
  32.  
  33. }
  34. }



另外一種解法:
  1. import java.util.Scanner;
  2.  
  3. public class Demo {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8.  
  9. int a = sc.nextInt();
  10. int b = sc.nextInt();
  11. int c = sc.nextInt();
  12.  
  13. System.out.println();
  14.  
  15. int max = a;
  16. int min = a;
  17.  
  18. if (b > max) {
  19. max = b;
  20. }
  21. if (c > max) {
  22. max = c;
  23. }
  24.  
  25. if (b < min) {
  26. min = b;
  27. }
  28. if (c < min) {
  29. min = c;
  30. }
  31.  
  32. System.out.printf("%d >= %d >= %d", max, a + b + c - max - min, min);
  33.  
  34. }
  35. }

1 則留言: