三目运算符加分支语句实例

发布于 2023-03-31  124 次阅读


题目

用三木运算符加上分支语句将输入的三个数从小到大按顺序排列

初步代码

#include<stdio.h>

int main()
{
	float a = 0, b = 0, c = 0, x1 = 0, x2 = 0, x3 = 0;
	scanf("%f %f %f", &a, &b, &c);

	x1 = (a > b && a > c) ? a : ((b > a && b > c) ? b : (c > a && c > b) ? c : 0);

	if ((a > b && a < c) || (a > c && a < b))
	{
		x2 = a;
	}
	else if ((b > a && b < c) || (b > c && b < a))
	{
		x2 = b;
	}
	else if ((c > a && c < b) || (c > b && c < a))
	{
		x2 = c;
	}

	if ((a == x1 && b == x2) || (a == x2 && b == x1))
	{
		x3 = c;
	}
	else if ((a == x1 && c == x2) || (a == x2 && c == x1))
	{
		x3 = b;
	}
	else if ((b == x1 && c == x2) || (b == x2 && b == x1))
	{
		x3 = a;
	}
	printf("x1=%5.2f\n", x1);
	printf("x2=%5.2f\n", x2);
	printf("x3=%5.2f\n", x3);

	printf("按从小到大为%5.2f,%5.2f,%5.2", x3, x2, x1);
	return 0;
}

错误

  1. 最终输出无法输出三个数
  2. 如果输入2 4 5,最后一个x3记为0了