正在阅读 Bermudez 的 C Programming Tutorial(KN King 的书的补充),并对第 5 章(选择语句)的第二个问题感到困惑。
问题如下:编写一个程序,读取五个值并按升序写出。
初出茅庐的程序员不允许使用数组或循环。唯一可用的工具是“if”和“switch”语句。
这是我的问题:我用蛮力解决了这个问题——这太不优雅了。一种猜测是我应该对这个练习感到不安;也就是说,也许 Bermudez 想向读者展示一个人需要做 5 次!完全依赖“if”和/或“switch”语句时的排列。
另一种猜测(可能是更有可能的猜测)是我做错了什么。有些东西告诉我,我至少可以将这段代码减半。
有什么建议吗?
最佳答案
这可能真的是作弊,但可以通过 Sorting Network 中的一小段代码来完成.
#include <stdio.h>
int main()
{
int a, b, c, d, e, temp;
printf("Program 5.2: Ascending Order of Values\n");
printf("======================================\n\n");
printf("Enter first value: ");
scanf("%d", &a);
printf("Enter second value: ");
scanf("%d", &b);
printf("Enter third value: ");
scanf("%d", &c);
printf("Enter fourth value: ");
scanf("%d", &d);
printf("Enter fifth value: ");
scanf("%d", &e);
printf("\nRe-arranged in ascending order: \n");
printf("===============================\n\n");
/* Sorting Network - 9 comparators */
if (a > b) { temp = a; a = b; b = temp; } // 0,1
if (d > e) { temp = d; d = e; e = temp; } // 3,4
if (c > e) { temp = c; c = e; e = temp; } // 2,4
if (c > d) { temp = c; c = d; d = temp; } // 2,3
if (a > d) { temp = a; a = d; d = temp; } // 0,3
if (a > c) { temp = a; a = c; c = temp; } // 0,2
if (b > e) { temp = b; b = e; e = temp; } // 1,4
if (b > d) { temp = b; b = d; d = temp; } // 1,3
if (b > c) { temp = b; b = c; c = temp; } // 1,2
printf("%d %d %d %d %d\n", a, b, c, d, e);
return 0;
}
关于c - Bermudez C 第 5 章 P 2 : No use of arrays or loops for ascending order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45136080/