c - 在 C 中查找最大和最小整数

标签 c integer

正如我在另一个问题中提到的,我一直在从 K.N King 的 C Programming: A Modern Approach (2ndEdn) 中自学 C。

我很享受,但如果合适的话,我希望在这里发布奇怪的问题以寻求建议,因为不幸的是我没有导师,有些人提出的问题比他们回答的多!

我正在回答一个问题,要求我编写一个程序来查找用户输入的四个整数中最大和最小的...我已经想出了一种方法来找到最大的,但对于生活我无法弄清楚如何获得最小的。问题说四个 if 语句应该足够了。数学不是我的强项,如有任何建议,我将不胜感激!

#include <stdio.h>

int main(int argc, const char *argv[])
{

    int one, two, three, four;

    printf("Enter four integers: ");

    scanf("%d %d %d %d", &one, &two, &three, &four);

    if (four > three && four > two && four > one)
            printf("Largest: %d", four);
    else if (three > four && three > two && three > one)
            printf("Largest: %d", three);
    else if (two > three && two > four && two > one)
            printf("Largest: %d", two);
    else
            printf("Largest: %d", one);

    return 0;

}

我尽量保持简单,因为我只读到第 5 章,共 27 章!

干杯 安德鲁

最佳答案

if (first > second)
    swap(&first, &second);
if (third > fourth)
    swap(&third, &fourth);
if (first > third)
    swap(&first, &third);
if (second > fourth)
    swap(&second, &fourth);

printf("Smallest: %d\n", first);
printf("Largest: %d\n", fourth);

swap() 函数的实现留作练习。

关于c - 在 C 中查找最大和最小整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5441323/

相关文章:

c++ - 使用 strdup() 后将 char* 转换为 int

c - 在 Asterisk 11 中从 H.264/AVC 转码到 HEVC

c - "implicit declaration of function"是什么意思?

c++ - 在 MATLAB 中解析具有十六进制浮点常量的文件

c - VC2008 中的链接器是否存在路径中的空格问题?

c - 请解释一下这段C代码

javascript - Jquery/Javascript - 无法递增数字 (tweet-id)

r - 我们可以得到R中的因子矩阵吗?

c++ - 在这种情况下,我将如何循环遍历所有各种可能性?

performance - 在现代编程中真的有 char 或 short 这样的东西吗?