正如我在另一个问题中提到的,我一直在从 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/