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

โปรแกรม C++ หาผลหารและเศษ (Quotient and Remainder)


ในการหาร มี 4 ส่วนประกอบ:

  • Dividend (ถูกหาร) - ตัวเลขที่ถูกหาร
  • Divisor (ตัวหาร) - ตัวเลขที่นำมาหาร
  • Quotient (ผลหาร) - ผลลัพธ์จากการหาร
  • Remainder (เศษ) - ส่วนที่เหลือจากการหาร

ความสัมพันธ์: dividend = divisor × quotient + remainder

ตัวอย่าง: 15 ÷ 7 → ผลหาร = 2, เศษ = 1

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

ใช้ตัวดำเนินการ / หาผลหาร และ % (modulus) หาเศษ