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

โปรแกรม C# หาค่าสูงสุดของเลข 3 ตัว

กำหนดตัวเลข 3 ตัว:

int num1 = 10, num2 = 20, num3 = 50;

ตรวจสอบหาค่าสูงสุดโดยเปรียบเทียบแบบ巢 (Nested if):

  • ถ้า num1 > num2 ให้เปรียบเทียบ num1 กับ num3
  • ถ้า num1 > num3 แสดงว่า num1 มากที่สุด
  • มิฉะนั้น num3 มากที่สุด
  • ถ้า num1 ไม่ > num2 ให้เปรียบเทียบ num2 กับ num3

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
    class MyApplication {
        static void Main(string[] args) {
            int num1, num2, num3;
            num1 = 10;
            num2 = 20;
            num3 = 50;
            if (num1 > num2) {
                if (num1 > num3) {
                    Console.Write("Number one is the largest!\n");
                } else {
                    Console.Write("Number three is the largest!\n");
                }
            } else if (num2 > num3) {
                Console.Write("Number two is the largest!\n");
            } else {
                Console.Write("Number three is the largest!\n");
            }
        }
    }
}

ผลลัพธ์

Number three is the largest!

วิธีทางเลือก: สามารถใช้ Math.Max(num1, Math.Max(num2, num3)) เพื่อหาค่าสูงสุดได้สั้นกว่า