c语言中进行大小排序的问题(少量排序)

  在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;
}

其实核心结构换汤不换药 , 要拿出一个临时值进行转化。在使用三元运算的时候要小心一点就是运算符优先的问题,当然你要是实在记不住通过小括号改变优先级。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值