-------------------------------------------------------------------------------------------------------
比较数的大小然后按一定的顺序输出,这样的方法有很多。例如冒泡排序,选择排序,if语句等;但是if语句只适合三个数或者以下的排序,三个数以上的排序建议使用冒泡排序。
-------------------------------------------------------------------------------------------------------
方法一:用if语句实现。
C语言代码如下:
# include <stdio.h> int main() { int a=4,b=9,c=-1; if(a>=b) { if(b>=c) { printf("%d %d %d", a, b, c); } else { printf("%d %d %d", a, c, b); } } else if(b>=c) { if(a>=c) { printf("%d %d %d", b, a, c); } else { printf("%d %d %d", b, c, a); } } if(c>=a) { if(a>=b) { printf("%d %d %d", c, a, b); } else { printf("%d %d %d", c, b, a); } } return 0; }
方法二:用冒泡排序实现。
C语言代码如下:
#include <stdio.h> #define SIZE 3 //宏定义素组大小为3 void bubble_sort(int a[], int n); //函数声明 void bubble_sort(int a[], int n) { int i, j, temp; for (j = 0; j < n - 1; j++) for (i = 0; i < n - 1 - j; i++) { if(a[i] > a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } int main() { int number[SIZE] = {4, 9, -1}; int i; bubble_sort(number, SIZE); for (i = SIZE-1; i >= 0; i--) { printf("%d ", number[i]); } printf("\n"); return 0; }
干货小知识:else只与离它最近的if匹配。一般情况下,0代表假,!0为真。
本文出自 “无名小卒” 博客,请务必保留此出处http://814193594.blog.51cto.com/10729329/1698919
原文:http://814193594.blog.51cto.com/10729329/1698919