Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình tìm số lớn nhất dùng toán tử ba ngôi trong C++

Viết chương trình tìm số lớn nhất trong 2, 3 hoặc 4 số sử dụng toán tử ba ngôi (ternary operator) trong C++.

Mô tả

Cho 2, 3 hoặc 4 số. Tìm max chỉ dùng toán tử `? :`.

Ví dụ

2 số: 4, 54 → 54

3 số: 14, 40, 26 → 40

4 số: 10, 54, 26, 62 → 62

Phương pháp

Biểu thức ternary lồng nhau:

  • 2 số (a,b): `a > b ? a : b`
  • 3 số (a,b,c): `(a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c)`
  • 4 số (a,b,c,d): `(a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d) ? c : d`

Chương trình 2 số

#include <iostream> 
using namespace std; 

int main() { 
    int a = 4, b = 9; 
    cout << "The greater element of the two elements is " << ((a > b) ? a : b); 
    return 0; 
}

Đầu ra: The greater element of the two elements is 9

Chương trình 3 số

#include <iostream> 
using namespace std; 

int findMax(int a, int b, int c) { 
    int maxVal = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); 
    return maxVal; 
} 

int main() { 
    int a = 4, b = 13, c = 7; 
    cout << "The greater element of the two elements is " << findMax(a, b, c); 
    return 0; 
}

Đầu ra: The greater element of the two elements is 13

Chương trình 4 số

#include <iostream> 
using namespace std; 

int findMax(int a, int b, int c, int d) { 
    int maxVal = ((a > b && a > c && a > d) ? a : (b > c && b > d) ? b : (c > d) ? c : d); 
    return maxVal; 
} 

int main() { 
    int a = 4, b = 13, c = 7, d = 53; 
    cout << "The greater element of the two elements is " << findMax(a, b, c, d); 
    return 0; 
}

Đầu ra: The greater element of the two elements is 53