c - Bermudez C 第 5 章 P 2 : No use of arrays or loops for ascending order

标签 c conditional

正在阅读 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;
}

Demo on ideone.com

关于c - Bermudez C 第 5 章 P 2 : No use of arrays or loops for ascending order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45136080/

相关文章:

iphone - iPhone越狱如何工作

c - Valgrind 错误

C 套接字 - 保留连接池以供重用 - s

c - C 中的简单堆栈结构程序返回 "(null)"而不是 peek() 值

xml - XSD 中的条件必需元素

c - 在 C 中,什么时候支持条件 "test ? : alt"形式(空的 true 大小写)?

c - printf 函数打印不应该打印的内容,为什么?

javascript - 如何检查某个 JS 文件是否包含在网页中?

dependency-injection - Spring boot @ConditionalOnBean 未检测到 bean 丢失,抛出异常 "No qualifying bean of type"

SQL 条件列存在