ผลหารและเศษที่เหลือเป็นส่วนหนึ่งของการหารพร้อมกับเงินปันผลและตัวหาร
จำนวนที่เราหารเรียกว่าเงินปันผล จำนวนที่หารเงินปันผลเรียกว่าตัวหาร ผลลัพธ์ที่ได้หลังจากการหารเรียกว่าผลหารและจำนวนที่เหลือคือเศษ
dividend = divisor * quotient + remainder
ตัวอย่างเช่น ถ้า 15 หารด้วย 7 แล้ว 2 จะเป็นผลหารและ 1 คือเศษเหลือ ในที่นี้ 15 คือเงินปันผลและ 7 เป็นตัวหาร
15 = 7 * 2 + 1
โปรแกรมหาผลหารและเศษมีดังนี้:
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int divisor, dividend, quotient, remainder;
dividend = 15;
divisor = 7;
quotient = dividend / divisor;
remainder = dividend % divisor;
cout << "Dividend is " << dividend <<endl;
cout << "Divisor is " << divisor <<endl;
cout << "Quotient is " << quotient << endl;
cout << "Remainder is " << remainder;
return 0;
} ผลลัพธ์
Dividend is 15 Divisor is 7 Quotient is 2 Remainder is 1
ในโปรแกรมข้างต้น ผลหารได้มาจากการหารเงินปันผลด้วยตัวหาร ส่วนที่เหลือได้มาจากการใช้ตัวดำเนินการโมดูลัสของเงินปันผลและตัวหาร
quotient = dividend / divisor; remainder = dividend % divisor;
หลังจากนั้นจะแสดงเงินปันผล ตัวหาร ผลหาร และเศษส่วน
cout << "Dividend is " << dividend <<endl; cout << "Divisor is " << divisor <<endl; cout << "Quotient is " << quotient << endl; cout << "Remainder is " << remainder;