排序三个数字的简单的方法 [英] Simpler way of sorting three numbers

查看:203
本文介绍了排序三个数字的简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个更简单的和更好的解决这个问题的方法,因为


  1. 我用了太多的变数。

  2. 我用这么多如果别人语句

  3. 我这样做是使用蛮力方法


  

写接收三个整数作为输入,递增的顺序输出数的程序。结果
  不要使用循环/阵列。


 的#include<&stdio.h中GT;
主要(){
   诠释NO1;
   诠释NO2;
   诠释NO3;
   诠释STO;
   INT喜;
   INT LO;   的printf(请输入1号:);
   scanf函数(%d个,&安培; NO1);
   的printf(进入2号);
   scanf函数(%d个,&安培; NO2);
   的printf(请输入3号:)​​;
   scanf函数(%d个,&安培; NO3);   如果(NO1> NO2){
      STO = NO1;
      LO = NO2;
   }其他{
      STO = NO2;
      LO = NO1;
   }
   如果(STO> NO3){
      HI = STO;
      如果(LO> NO3){
         STO = LO;
         LO = NO3;
      }其他{
         STO = NO3;
      }
   }其他HI = NO3;   的printf(最小%d个\\ N,LO);
   的printf(MIDDLE%d个\\ N,STO);
   的printf(最高%d个\\ N,喜);   残培();
}


解决方案

 如果(A> C)
   掉期(A,C)如果(A> B)
   掉期(A,B)//现在最小的元素是第一个。只是检查2次和3次如果(B> C)
   掉期(B,C);


  

注:交换改变了两个值
  变数。


Is there a simpler and better way to solve this problem because

  1. I used too many variables.
  2. I used so many if else statements
  3. I did this using the brute force method

Write a program that receives three integers as input and outputs the numbers in increasing order.
Do not use loop / array.

#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(); 
}    

解决方案

if (a > c)
   swap(a, c)

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

//Now the smallest element is the first one. Just check the 2-nd and 3-rd

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

Note: Swap changes the values of two variables.

这篇关于排序三个数字的简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆