如何在不使用++或+或C / C ++中的任何其他算术运算符的情况下将两个数字相加?
在本文中,我们将看到如何在不使用算术运算符(例如+,++,-或-)的情况下将两个数字相加。
为了解决这个问题,我们可以使用二进制加法器逻辑来解决它们。在这种情况下,我们被设计为半加法器和全加法器。这些加法器可以加一位二进制数。通过级联多个加法器,我们可以创建电路以添加更大的数字。
在该加法器中,我们在数字之间执行了XOR运算,然后对于进位执行了ANDing逻辑。此处实现了这些功能以添加两个数字。
范例程式码
#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
热门推荐
10 送师姐的祝福语简短
11 生日祝福语短句简短霸气
12 过年祝福语南昌话简短
13 老婆生日祝福语简短孩子
14 新年祝福语简短创意兄弟
15 开业经典祝福语简短
16 双节祝福语简短英文
17 给儿子生日祝福语 简短
18 求助短信生日祝福语简短