温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c - Simpler way of sorting three numbers
c

c - 对三个数字进行排序的更简单方法

发布于 2020-03-27 16:12:01

有没有更简单,更好的方法来解决此问题,因为

  1. 我使用了太多变量。
  2. 我用了很多if else
  3. 我是用蛮力法做的

编写一个程序,该程序接收三个整数作为输入,并按升序输出数字。
不要使用循环/数组。

#include <stdio.h>
main(){
   int no1;
   int no2;
   int no3;
   int sto;
   int hi;
   int lo;

   printf("Enter No. 1: ");
   scanf("%d", &no1);
   printf("Enter No. 2: ");
   scanf("%d", &no2);         
   printf("Enter No. 3: ");
   scanf("%d", &no3);

   if (no1>no2) {   
      sto=no1;    
      lo=no2;   
   } else {
      sto=no2;  
      lo=no1;  
   } 
   if (sto>no3) { 
      hi=sto;    
      if(lo>no3){         
         sto=lo;                
         lo=no3;
      }else {
         sto=no3;      
      }         
   }else hi=no3; 

   printf("LOWEST %d\n", lo);
   printf("MIDDLE %d\n", sto);
   printf("HIGHEST %d\n", hi);  

   getch(); 
}    

查看更多

查看更多

提问者
newbie
被浏览
14
41 2020-01-04 10:36
if (a > c)
   swap(a, c);

if (a > b)
   swap(a, b);

//Now the smallest element is the 1st one. Just check the 2nd and 3rd

if (b > c)
   swap(b, c);

注意:交换会更改两个变量的值。