ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

三个数由小到大排序

2021-08-14 22:02:12  阅读:227  来源: 互联网

标签:temp int 代码 largest else 三个 printf 由小到大 排序


《C语言经典编程282例》第十题:三个数由小到大排序

在写这个题目时,我很自然的想到a是三个数里最大的,然后依次比较b、c的大小并重复。于是将代码写成了

#include <stdio.h>
int main(){
    int a = 50;
    int b = 92;
    int c = 83;
    int temp = 0;//set temp
    if(a > b && a > c){  //a is largest
        if(b > c){      //b is bigger than c
            //change a and c
            temp = a;
            a = c;
            c = temp;
        } else if(b < c){ //a >c >b
            temp = b;
            b = c;
            c = temp;
            temp = a;
            a = c;
            c = temp;
        }
    } else if(b > a && b > c){  //b is the largest
        if(a < c){      //b > c > a
            temp = b;
            b = c;
            c = temp;
        } else if(a > c){       //b >a >c
            temp = a;
            a = c;
            c = temp;
            temp = b;
            b = c;
            c = temp;
        }
    } else{   //c is the largest
        if(a > b){
            temp = a;
            a = b;
            b = temp;
        }
    }
    printf("a: %d  b:%d  c:%d",a,b,c);
}
我自己写的

写完之后看了一眼参考代码,它是这样的

#include <stdio.h>
int main(){
    int a,b,c,temp;
    printf("Please input a,b,c:\n");
    scanf("%d%d%d",&a,&b,&c);
    if(a > b){  //依次比较两个数
        temp = a;
        a = b;
        b = temp;
    }
    if(a > c){
        temp = a;
        a = c;
        c = temp;
    }
    if(b > c){
        temp = b;
        b = c;
        c = temp;
    }
    printf("The order of the number is:%d,%d,%d\n",a,b,c);
    return 0;
}
View Code

比较两段,不难看出第二段代码更为优秀一些。

于是就反思我写的代码不足之处在哪呢?

无疑编程经验的不足以及思考问题太过简单化是造成这次事故的主要诱因。

比较大小,就直奔主题找到最大的数字,不去思其他的方面。

思维的高度还有待提高。

标签:temp,int,代码,largest,else,三个,printf,由小到大,排序
来源: https://www.cnblogs.com/pfapos/p/15141989.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有