如何在不使用++或+或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 送给学长毕业祝福语简短