使用位運算子執行加法運算的 C++ 程式


位運算子用於執行位運算。這意味著對位進行操作。一些位運算子有位 AND、位 OR、位 XOR 等。

下面給出使用位運算子進行加法運算的程式 −

示例

 即時演示

#include<iostream>
using namespace std;
int main() {
   int num1, num2, carry;
   cout << "Enter first number:"<<endl;
   cin >> num1;
   cout << "Enter second number:"<<endl;
   cin >> num2;

   while (num2 != 0) {
      carry = num1 & num2;
      num1 = num1 ^ num2;
      num2 = carry << 1;
   }
   cout << "The Sum is: " << num1;
   return 0;
}

輸出

以上程式的輸出如下 −

Enter first number:11
Enter second number: 5
The Sum is: 16

在上述程式中,兩個數字是從使用者獲得。如下所示 −

cout << "Enter first number:"<<endl;
cin >> num1;

cout << "Enter second number:"<<endl;
cin >> num2;

之後,使用 while 迴圈執行加法運算。它涉及使用位 AND、位 XOR 和左移運算子。程式碼片段如下 −

while (num2 != 0) {
   carry = num1 & num2;
   num1 = num1 ^ num2;
   num2 = carry << 1;
}

最後,顯示和。如下所示 −

cout << "The Sum is: " << num1;

更新於: 25-6-2020

2K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.