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

หาค่าเฉลี่ยของสองจำนวนโดยไม่ใช้การหารใน C++

โจทย์

ได้รับตัวเลข A และ B ทางเราต้อง หาค่าเฉลี่ยโดยไม่ใช้ตัวดำเนินการหาร

ตัวอย่าง

Input: A = 34, B = 54

Output: 44

แนวทางแก้ปัญหา

ค่าเฉลี่ยปกติคือ (A+B)/2 การหาร 2 เทียบเท่ากับ Right Shift 1 bit (>> 1) ในระบบฐานสอง

สูตร: average = (A + B) >> 1

ข้อควรระวัง: ใช้กับ Signed Integer ได้ถ้าไม่มี Overflow และค่าบวก (Arithmetic Shift รักษา Sign Bit)

โปรแกรมตัวอย่าง

#include <iostream>
using namespace std;

int calcAvgWODiv(int A, int B) {
    int average = (A + B) >> 1;
    return average;
}

int main() {
    int A = 123, B = 653;
    cout << "The average of the number is " << calcAvgWODiv(A, B);
    return 0;
}

ผลลัพธ์

The average of the number is 388