【题目描述】
输入三个整数,按从大到小的顺序输出。
【输入】
输入三个整数
【输出】
按从大到小的顺序输出。
【输入样例】
3 2 1
【输出样例】
3 2 1
【程序分析】
【程序实现】
三次比较和交换(冒泡排序)
#include <stdio.h>
int main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
// 使用冒泡排序思想进行三次比较交换
if (a < b) { // 确保a >= b
int temp = a;
a = b;
b = temp;
}
if (a < c) { // 确保a >= c
int temp = a;
a = c;
c = temp;
}
if (b < c) { // 确保b >= c
int temp = b;
b = c;
c = temp;
}
printf("%d %d %d\n", a, b, c);
return 0;
}
中间变量法:
#include <stdio.h>
int main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
int first, second, third;
// 找出最大值
if (a >= b && a >= c) {
first = a;
if (b >= c) {
second = b;
third = c;
} else {
second = c;
third = b;
}
} else if (b >= a && b >= c) {
first = b;
if (a >= c) {
second = a;
third = c;
} else {
second = c;
third = a;
}
} else {
first = c;
if (a >= b) {
second = a;
third = b;
} else {
second = b;
third = a;
}
}
printf("%d %d %d\n", first, second, third);
return 0;
}
1066

被折叠的 条评论
为什么被折叠?



