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

ตรวจสอบ Integer Overflow ใน Multiplication ใน C++

ต้องการตรวจสอบว่า Multiplication ของ A และ B จะเกิน 64-bit Integer หรือไม่ ตัวอย่าง 100×200 ไม่เกิน แต่ 10000000000 × -10000000000 จะ Overflow

ขั้นตอนตรวจสอบ:

  1. ถ้าใดๆ เป็น 0 ไม่เกิน
  2. ถ้า (A×B)/B == A ไม่เกิน
  3. กรณีอื่นๆ จะเกิน

ตัวอย่างโค้ด C++

#include <iostream>
#include <cmath>
using namespace std;

bool isMulOverflow(long long A, long long B) {
    if (A == 0 || B == 0)
        return false;
    long long result = A * B;
    if (A == result / B)
        return false;
    else
        return true;
}

int main() {
    long long a = 10000000000, b = -10000000000;
    if(isMulOverflow(a, b)) {
        cout << "It will overflow";
    } else {
        cout << "It will not overflow";
    }
}

ผลลัพธ์

It will overflow