Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 최소 비교를 사용하는 3의 중간

<시간/>

이번 절에서는 주어진 세 값의 중간값을 비교하여 찾는 방법을 알아보겠습니다. 따라서 (10, 30, 20)과 같이 세 개의 숫자가 주어지면 이것이 중간 요소이므로 20을 찾습니다. 먼저 알고리즘을 살펴본 다음 해당 알고리즘을 C++ 코드로 구현하겠습니다.

알고리즘

middle_of_three(a, b, c):
Input: Three numbers a, b and c
Output: The middle of these three
Begin
   if a > b, then
      if b > c, then
         return b
      else if a > c, then
         return c
      else
         return a
      else
         if a > c, then
            return a
         else if b > c, then
            return c
      else
         return b
End

예시

#include <iostream>
using namespace std;
int mid_three(int a, int b, int c) {
   if (a > b) {
      if (b > c)
         return b;
      else if (a > c)
         return c;
      else
         return a;
   } else {
      if (a > c)
         return a;
      else if (b > c)
         return c;
      else
         return b;
   }
}
main() {
   int a = 10, b = 30, c = 20;
   cout << "Middle Out of Three "<< mid_three(a, b, c);
}

출력

Middle Out of Three 20