查找C中的最大和最小整数

aus*_*_aj 9 c integer

正如我在另一个问题中提到的,我一直在用KN King's 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;

}
Run Code Online (Sandbox Code Playgroud)

我试图保持简单,因为我只有27章的第5章!

干杯安德鲁

mgr*_*ber 15

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);
Run Code Online (Sandbox Code Playgroud)

swap()功能的实现留作练习.


Jor*_*nas 2

另一种方式是这样的:

int one, two, three, four;  
//Assign values to the four variables;  
int largest, smallest;  
largest = max(max(max(one, two), three), four);  
smallest = min(min(min(one, two), three), four);  
Run Code Online (Sandbox Code Playgroud)

不需要一个 if 语句;)

  • 您确实意识到他编写代码不是为了快速或简洁,而是为了学习语言功能。 (2认同)