การหาตัวเลขมากที่สุดใน 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
ตรรกะการทำงาน:
- เปรียบเทียบ
aกับbก่อน - ถ้า
a > bให้เปรียบเทียบaกับc→ ถ้าa > cแสดงว่าaมากที่สุด มิฉะนั้นcมากที่สุด - ถ้า
a <= bแสดงว่าb >= aให้เปรียบเทียบbกับc→ ถ้าb > cแสดงว่าbมากที่สุด มิฉะนั้นcมากที่สุด