Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมหาตัวเลขมากที่สุดด้วย Ternary Operator ใน C++


คำอธิบายโจทย์

หาค่าสูงสุดของ 2, 3, หรือ 4 ตัวเลข โดยใช้ Ternary Operator (?:) เท่านั้น

ตัวอย่าง

  • 2 numbers: 4, 54 → 54
  • 3 numbers: 14, 40, 26 → 40
  • 4 numbers: 10, 54, 26, 62 → 62

สูตร Ternary Operator

2 ตัว: a > b ? a : b

3 ตัว: (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c)

4 ตัว: (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d) ? c : d

โค้ดตัวอย่าง

2 ตัวเลข

#include <iostream>
using namespace std;
int main() {
    int a=4, b=9;
    cout << "Max: " << ((a>b) ? a : b);
    return 0;
}

3 ตัวเลข

#include <iostream>
using namespace std;
int findMax(int a, int b, int c) {
    return (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c);
}
int main() {
    cout << findMax(4, 13, 7); // 13
    return 0;
}

4 ตัวเลข

#include <iostream>
using namespace std;
int findMax(int a, int b, int c, int d) {
    return (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d) ? c : d;
}
int main() {
    cout << findMax(4, 13, 7, 53); // 53
    return 0;
}