如何在不使用++或+或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 教师闺蜜祝福语简短