在c语言的学习过程中,我们学习通过if else条件语句对输入的数据进行排序,一般来说是通过if else进行实现,代码如下:
要求:1.输入3个整数 a b c。
2.对三位整数进行排序 a最小 依次变大。
按照我们所学if else进行实现
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int a , b , c;
printf("输入三个整数:");
scanf("%d%d%d" , &a , &b , &c);
int temp;
//下面俩次比较实现a为a ,b ,c中的最小值
if(a > b)
{
temp = a; a = b ; b = temp;
}
if(a > c)
{
temp = a; a = c; c = temp;
}
//下面一次比较实现b为b , c中的最小值
if(b > c)
{
temp = b; b =c; c = temp;
}
printf("从小到大依次为: %d %d %d\n" , a , b , c);
return 0;
}
我自己把if 分支结构转化成三元运算符进行实现大小排序。
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int a , b ,c;
printf("请输入三个整数;");
scanf("%d%d%d" , &a, &b , &c);
int temp;
a > b ? temp == a + b , a == temp - a , b == temp - b : a == a , b = b;
temp = 0;
b > c ? temp == b + c , b == temp - b , c == temp - c : b == b , c = c;
temp = 0;
a > b ? temp == a + b , a == temp - a , b == temp - b : a == a , b = b;
printf("大小排数为: %d%d%d" , c , b , a );
return 0;
}
其实核心结构换汤不换药 , 要拿出一个临时值进行转化。在使用三元运算的时候要小心一点就是运算符优先的问题,当然你要是实在记不住通过小括号改变优先级。