Java教程

三个数由小到大排序

本文主要是介绍三个数由小到大排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

《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

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

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

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

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

思维的高度还有待提高。

这篇关于三个数由小到大排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!