C语言:排序 交换两个变量的函数 指针应用
#include <stdio.h> //从大到小排序 void swap(int *a,int *b) { int tmp = *a; *a = *b; *b = tmp; } int main() { int a,b,c; scanf("%d,%d,%d",&a,&b,&c); if(a<b) swap(&a,&b); if(c>a) swap(&a,&c); if(c>b) swap(&c,&b); printf("从大到小的顺序为:%d,%d,%d\n",a,b,c); printf("从小到大的顺序为:%d,%d,%d\n",c,b,a); getchar(); }
#include <stdio.h> int main() { int a,b,c,d; scanf("%d,%d,%d",&a,&b,&c); (c>b)?(d=b,b=c,c=d):1,(c>a)?(d=a,a=c,c=d):1,(a<b)?(d=a,a=b,b=d):1; printf("%d,%d,%d",a,b,c); getchar(); }
#include <stdio.h> int main() { int a,b,c; scanf("%d,%d,%d",&a,&b,&c); printf("%d,%d,%d",a>b?(a>c?a:c):(b>c?b:c),a>b?(a<c?a:(b>c?b:c)):(a>c?a:(b>c?c:b)),a<b?(a<c?a:c):(b<c?b:c)); getchar(); }
说明:第一项求最大值:a>b?(a>c?a:c):(b>c?b:c),a>b a>c成立时最大值为a,a>b a<c最大值为c,a<b b>c时最大值为b, a<b b<c时最大值为c
第二项求中间值:a>b?(a<c?a:(b>c?b:c)):(a>c?a:(b>c?c:b)) :
a>b a<c:a为中间值;a>b a>c b>c:b为中间值;a>b a>c b<c:c为中间值
a<b a>c :a为中间值l a<b a<c b>c:c为中间值;a<b a<c b<c:b为中间值
第三项求最小值:a<b?(a<c?a:c):(b<c?b:c) ,a<b a<c :a为最小值;a<b a>c:c为最小值; a>b b<c :b为最小值; a>b b>c:c为最小值