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

หาค่าสูงสุดของ 4 ตัวเลขโดยไม่ใช้เงื่อนไขหรือบิตเวิร์ส C++


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

หาค่าสูงสุดของ 4 ตัวเลข a,b,c,d ห้ามใช้ if/else, ternary, bitwise operators

ตัวอย่าง

a=4, b=7, c=1, d=9 → Output: 9

วิธีแก้ปัญหา

ใช้ boolean index ของอาร์เรย์ขนาด 2:

  • bool MaxIndex = !(arr[0]-arr[1] + abs(arr[0]-arr[1]));
  • ถ้า arr[0]>arr[1] → ค่าในวงเล็บ >0 → !true = false (0) → arr[0]
  • ถ้า arr[0]≤arr[1] → ค่า ≤0 → !false = true (1) → arr[1]

ทำซ้ำคู่ไปเรื่อยๆ: max(a,b) → max(max,c) → max(max,d)

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

#include <iostream>
#include <cmath>
using namespace std;

int findMax(int x, int y) {
    int arr[2] = {x, y};
    bool MaxIndex = !(arr[0] - arr[1] + abs(arr[0] - arr[1]));
    return arr[MaxIndex];
}

int CalcMaxElement(int a, int b, int c, int d) {
    int max = a;
    max = findMax(max, b);
    max = findMax(max, c);
    max = findMax(max, d);
    return max;
}

int main() {
    int a=4, b=9, c=7, d=1;
    cout << "Maximum: " << CalcMaxElement(a,b,c,d);
    return 0;
}

ผลลัพธ์

Maximum: 9