ในบทความนี้ เราจะเรียนรู้วิธีคำนวณผลหาร (Quotient) และเศษ (Remainder) ในภาษา Java
สูตร
- Quotient = Dividend / Divisor
- Remainder = Dividend % Divisor
โดยที่ Dividend = ตัวตั้ง, Divisor = ตัวหาร
ตัวอย่างการทำงาน
อินพุต:
Dividend value: 50 Divisor: 3
เอาต์พุต:
Quotient: 16 Remainder: 2
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปรจำนวนเต็ม 4 ตัว:
my_dividend,my_divisor,my_quotient,my_remainder - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- คำนวณผลหารและเศษด้วยสูตรข้างต้น
- แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class RemainderQuotient {
public static void main(String[] args) {
int my_dividend, my_divisor, my_quotient, my_remainder;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined");
System.out.print("Enter the value of dividend: ");
my_dividend = my_scanner.nextInt();
System.out.print("Enter the value of divisor: ");
my_divisor = my_scanner.nextInt();
my_quotient = my_dividend / my_divisor;
my_remainder = my_dividend % my_divisor;
System.out.println("The quotient is " + my_quotient);
System.out.println("The remainder is " + my_remainder);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class RemainderQuotient {
public static void main(String[] args) {
int my_dividend = 50, my_divisor = 3, my_quotient, my_remainder;
System.out.println("The dividend and the divisor are defined as " + my_dividend + " and " + my_divisor);
my_quotient = my_dividend / my_divisor;
my_remainder = my_dividend % my_divisor;
System.out.println("The quotient is " + my_quotient);
System.out.println("The remainder is " + my_remainder);
}
}
ทั้งสองตัวอย่างให้ผลลัพธ์: Quotient = 16, Remainder = 2 (เพราะ 50 = 16×3 + 2)