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

โปรแกรม C++ หาตัวเลขมากที่สุดใน 3 จำนวน


การหาตัวเลขมากที่สุดใน 3 จำนวน สามารถทำได้โดยใช้คำสั่ง if 巢狀 (nested if)

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

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 1, c = 9;
    if (a > b) {
        if (a > c)
            cout << a << " is largest number";
        else
            cout << c << " is largest number";
    } else {
        if (b > c)
            cout << b << " is largest number";
        else
            cout << c << " is largest number";
    }
    return 0;
}

ผลลัพธ์

9 is largest number

ตรรกะการทำงาน:

  1. เปรียบเทียบ a กับ b ก่อน
  2. ถ้า a > b ให้เปรียบเทียบ a กับ c → ถ้า a > c แสดงว่า a มากที่สุด มิฉะนั้น c มากที่สุด
  3. ถ้า a <= b แสดงว่า b >= a ให้เปรียบเทียบ b กับ c → ถ้า b > c แสดงว่า b มากที่สุด มิฉะนั้น c มากที่สุด