C语言中将三个数字进行排序的几种写法

2018-03-16  本文已影响0人  茶新味_fc3a

网上关于这一问题的写法其实很多,但是很多方法不具有实际的应用价值(比如单纯使用if和else语句写出六种可能做判别),当然这也不失为一种思路,这里仅罗列出三种具有代表性的处理方法(三目运算法、IF比较法、和IF比较的指针写法)

//if语句依次比较大小排序  
#include <stdio.h>  
int compare(int x,int y,int z)  
{  
    int t=0;  
    if(x<y)  
    {  
        t=x;x=y;y=t;  
    }  
    if(y<z)  
    {  
        t=y;y=z;z=t;  
    }  
    if(x<y)  
    {  
        t=x;x=y;y=t;  
    }  
    printf("the number from big to small is\n %d %d %d \n",x,y,z);  
}  
  
int main()  
{  
    int a,b,c;  
    printf("please input three numbers \n");  
    scanf("%d %d %d",&a,&b,&c);  
    compare(a,b,c);  
    return 0;  
}  
//三目运算比大小  
#include <stdio.h>  
  
int max(int x,int y,int z)  
{  
    int max=0;  
    max=x>y?x:y;  
    max=max>z?max:z;  
    return max;  
}  
  
int smaller(int x,int y,int z)  
{  
    int smaller=0;  
    smaller=x<y?x:y;  
    smaller=smaller<z?smaller:z;  
    return smaller;  
}  
  
int middle(int x,int y,int z)  
{  
    int middle=0;  
    middle=x+y+z-smaller(x,y,z)-max(x,y,z);  
    return middle;  
}  
  
int main()  
{  
    int a,b,c;  
    printf("please input three numbers \n");  
    scanf("%d %d %d",&a,&b,&c);  
    printf("the number from max to small is %d %d %d \n",max(a,b,c),middle(a,b,c),smaller(a,b,c));  
    return 0;  
}  
#include <stdio.h>  
int compare(intint *x,intint *y,intint *z)  
{  
    int t;  
    if(*x<*y)  
    {  
        t=*x;*x=*y;*y=t;  
    }  
    if(*y<*z)  
    {  
        t=*y;*y=*z;*z=t;  
    }  
    if(*x<*y)  
    {  
        t=*x;*x=*y;*y=t;  
    }  
    printf("the number from big to small is\n%d %d %d \n",*x,*y,*z);  
}  
  
  
int main()  
{  
    int a,b,c;  
    printf("please input three numbers \n");  
    scanf("%d %d %d",&a,&b,&c);  
    compare(&a,&b,&c);  
    return 0;  
}  
上一篇 下一篇

猜你喜欢

热点阅读