C语言设计 (第四版) 谭浩强 习题2.4(3)
习题 2.4(3) 有3个数a, b, c,要求按大小顺序把它们输出。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:使用条件语句
#include <stdio.h>
#include <stdlib.h>
typedef int Type; //类型模板,可调整为其他类型
int main(){
Type a, b, c;
scanf_s("%d %d %d", &a, &b, &c);
//以下代码块为从大到小排列
printf("Arrange from large to small: ");
if(a > b){
if(a > c){
if(b > c){
printf("%d %d %d\n", a, b, c);
}
else{
printf("%d %d %d\n", a, c, b);
}
}
else{
printf("%d %d %d\n", c, a, b);
}
}
else{
if(b > c){
if(a > c){
printf("%d %d %d\n", b, a, c);
}
else{
printf("%d %d %d\n", b, c, a);
}
}
else{
printf("%d %d %d\n", c, b, a);
}
}
//以下代码块为从小到大排列
printf("Arrange from small to large: ");
if(a < b){
if(a < c){
if(b < c){
printf("%d %d %d\n", a, b, c);
}
else{
printf("%d %d %d\n", a, c, b);
}
}
else{
printf("%d %d %d\n", c, a, b);
}
}
else{
if(a > c){
if(b > c){
printf("%d %d %d\n", c, b, a);
}
else{
printf("%d %d %d\n", b, c, a);
}
}
else{
printf("%d %d %d\n", b, a, c);
}
}
system("pause");
return 0;
}
方法2:使用宏定义、类型模板、指针、函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
#define N 3 //定义输入数的数量
#define FORMAT "%d" //定义输出格式符,可调整为其他类型
typedef int Type; //类型模板,可调整为其他类型
//输入函数
void input(Type *arr, int n){
for(int i = 0; i < n; i++){
scanf_s(FORMAT, &arr[i]);
}
}
//由大到小排列函数
void largeToSmall(Type *arr, int n){
Type temp;
for(int i = 0; i < n - 1; i++){
for(int j = i + 1; j < n; j++){
if(arr[i] < arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
//由小到大排列函数
void smallToLarge(Type *arr, int n){
Type temp;
for(int i = 0; i < n - 1; i++){
for(int j = i + 1; j < n; j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
//输出函数
void output(Type *arr, int n){
for(int i = 0; i < n; i++){
printf(FORMAT, arr[i]);
printf(" ");
}
printf("\n");
}
int main(){
Type *arr = (Type*)malloc(N * sizeof(Type));
input(arr, N);
printf("Arrange from large to small: ");
largeToSmall(arr, N);
output(arr, N);
printf("Arrange from small to large: ");
smallToLarge(arr, N);
output(arr, N);
free(arr);
system("pause");
return 0;
}
方法3:使用条件表达式、函数的模块化设计。注:极简写法,不推荐,代码阅读理解会很困难,代码的原则之一,要容易理解。
#include <stdio.h>
#include <stdlib.h>
typedef int Type;
//由大到小排列函数
void largeToSmall(Type a, Type b, Type c){
printf("Arrange from large to small: ");
a > b ? (a > c ? (b > c ? printf("%d %d %d\n", a, b, c) : printf("%d %d %d\n", a, c, b)) : printf("%d %d %d\n", c, a, b)) : (b > c ? (a > c ? printf("%d %d %d\n", b, a, c) : printf("%d %d %d\n", b, c, a)) : printf("%d %d %d\n", c, b, a));
}
//由小到大排列函数
void smallToLarge(Type a, Type b, Type c){
printf("Arrange from small to large: ");
a < b ? (a < c ? (b < c ? printf("%d %d %d\n", a, b, c) : printf("%d %d %d\n", a, c, b)) : printf("%d %d %d\n", c, a, b)): (b < c ? (a < c ? printf("%d %d %d\n", b, a, c) : printf("%d %d %d\n", b, c, a)) : printf("%d %d %d\n", c ,b, a));
}
int main(){
Type a, b, c;
scanf_s("%d %d %d", &a, &b, &c);
largeToSmall(a, b, c);
smallToLarge(a, b, c);
system("pause");
return 0;
}