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





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


    
    
  1. //if语句依次比较大小排序
  2. #include <stdio.h>
  3. int compare( int x, int y, int z)
  4. {
  5. int t= 0;
  6. if(x<y)
  7. {
  8. t=x;x=y;y=t;
  9. }
  10. if(y<z)
  11. {
  12. t=y;y=z;z=t;
  13. }
  14. if(x<y)
  15. {
  16. t=x;x=y;y=t;
  17. }
  18. printf( "the number from big to small is\n %d %d %d \n",x,y,z);
  19. }
  20. int main()
  21. {
  22. int a,b,c;
  23. printf( "please input three numbers \n");
  24. scanf( "%d %d %d",&a,&b,&c);
  25. compare(a,b,c);
  26. return 0;
  27. }

    
    
  1. //三目运算比大小
  2. #include <stdio.h>
  3. int max( int x, int y, int z)
  4. {
  5. int max= 0;
  6. max=x>y?x:y;
  7. max=max>z?max:z;
  8. return max;
  9. }
  10. int smaller( int x, int y, int z)
  11. {
  12. int smaller= 0;
  13. smaller=x<y?x:y;
  14. smaller=smaller<z?smaller:z;
  15. return smaller;
  16. }
  17. int middle( int x, int y, int z)
  18. {
  19. int middle= 0;
  20. middle=x+y+z-smaller(x,y,z)-max(x,y,z);
  21. return middle;
  22. }
  23. int main()
  24. {
  25. int a,b,c;
  26. printf( "please input three numbers \n");
  27. scanf( "%d %d %d",&a,&b,&c);
  28. printf( "the number from max to small is %d %d %d \n",max(a,b,c),middle(a,b,c),smaller(a,b,c));
  29. return 0;
  30. }


    
    
  1. //指针的使用与指针解引用
  2. #include <stdio.h>
  3. int compare( int *x, int *y, int *z)
  4. {
  5. int t;
  6. if(*x<*y)
  7. {
  8. t=*x;*x=*y;*y=t;
  9. }
  10. if(*y<*z)
  11. {
  12. t=*y;*y=*z;*z=t;
  13. }
  14. if(*x<*y)
  15. {
  16. t=*x;*x=*y;*y=t;
  17. }
  18. printf( "the number from big to small is\n%d %d %d \n",*x,*y,*z);
  19. }
  20. int main()
  21. {
  22. int a,b,c;
  23. printf( "please input three numbers \n");
  24. scanf( "%d %d %d",&a,&b,&c);
  25. compare(&a,&b,&c);
  26. return 0;
  27. }





  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值