简体   繁体   English

在 C 编程中找到五个数字中最大和第二大的数字

[英]find the largest and the second largest numbers out of five numbers in C programming

I want to write a C program which can find the largest and the second-largest numbers among the five numbers.我想写一个 C 程序,它可以找到五个数字中最大和第二大的数字。 that would be great if I could've written this only using if-else operators.如果我只能使用 if-else 运算符来编写它,那就太好了。

like this(but it should be 5 numbers and it should find the second largest number)像这样(但它应该是 5 个数字,它应该找到第二大的数字)

int main() {
  int a, b, c;
  int min, max;
  printf("Uc sayi girin: ");
  scanf("%d%d%d", & a, & b, & c);
  printf("Ortalama: %f\n", (a + b + c) / 3.0);

  if (a < b) {
    min = a;
    max = b;
  } else {
    min = b;
    max = a;
  }
  if (c < min)
    min = c;
  else if (c > max)
    max = c;

  printf("The smallest number: %d\n", min);
  printf("The greatest number: %d\n", max);

  system("pause");
  return 0;
}

It's easier to do this in a for loop;for循环中更容易做到这一点;

#include <stdio.h>
#include <stdlib.h>

int main() {
  int a[5] = { 2, 4, -3, -5, 9 };
  int m0 = 0x80000000; // set to min
  int m1 = 0x80000000; // set to min
  int t; // temporary var

  for (int i = 0; i < 5; i++) {
    if (m1 < a[i]) {
      m1 = a[i];

      if (m0 < m1) {
        t = m0;
        m0 = m1;
        m1 = t;
      }
    }
  }

  printf("max = %d second max = %d\n", m0, m1);

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM