如何在不使用 ++ 運算子、+運算子或 C/C++ 中的任何其他算術運算子的情況下為兩個數字求和?
在本文中,我們將看到在不使用 +, ++, -, 或 -- 等算術運算子的情況下,如何為兩個數字求和。
為了解決這個問題,我們可以使用二進位制加法器邏輯來解決它們。在這種情況下,我們設計了半加法器和全加法器。這些加法器可以為一位二進位制數求和。透過級聯多個加法器,我們可以建立電路來計算更大的數字。
在該加法器中,我們在數字之間執行 XOR 操作,然後為進位執行 AND 操作。此處的這些特性用於計算兩個數字的和。
示例程式碼
#include <iostream> using namespace std; int add(int a, int b) { while (b != 0) { //until there is no carry, iterater int carry = a & b; //find carry by anding a and b a = a ^ b; //perform XOR on a and b, and store into a b = carry << 1; //the carry is shifted one bit to the left, and store it to b } return a; } int main() { int a, b; cout << "Enter two numbers to add: "; cin >> a >> b; cout << "The result is: " << add(a, b); return 0; }
輸出
Enter two numbers to add: 56 23 The result is: 79
廣告