ขั้นแรก ตั้งค่าตัวเลขสองตัว
int one = 250; int two = 200;
ตอนนี้ส่งตัวเลขเหล่านั้นไปยังฟังก์ชันต่อไปนี้
public int RemainderFunc(int val1, int val2) {
if (val2 == 0)
throw new Exception("Second number cannot be zero! Cannot divide by zero!");
if (val1 < val2)
throw new Exception("Number cannot be less than the divisor!");
else
return (val1 % val2);
} ด้านบนเราได้ตรวจสอบเงื่อนไขสองประการคือ
- ถ้าตัวเลขที่สองเป็นศูนย์ ข้อยกเว้นจะเกิดขึ้น
- ถ้าตัวเลขแรกน้อยกว่าตัวเลขที่สอง ข้อยกเว้นจะเกิดขึ้น
หากต้องการคืนค่าที่เหลือของตัวเลขสองตัว ให้กรอกโค้ดด้านล่าง
ตัวอย่าง
using System;
namespace Program {
class Demo {
public int RemainderFunc(int val1, int val2) {
if (val2 == 0)
throw new Exception("Second number cannot be zero! Cannot divide by zero!");
if (val1 < val2)
throw new Exception("Number cannot be less than the divisor!");
else
return (val1 % val2);
}
static void Main(string[] args) {
int one = 250;
int two = 200;
int remainder;
Console.WriteLine("Number One: "+one);
Console.WriteLine("Number Two: "+two);
Demo d = new Demo();
remainder = d.RemainderFunc(one, two);
Console.WriteLine("Remainder: {0}", remainder );
Console.ReadLine();
}
}
} ผลลัพธ์
Number One: 250 Number Two: 200 Remainder: 50