如何在不使用++或+或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
热门推荐
3 祝福语简短的微信
10 9字祝福语简短创意
11 朋友聚会祝福语简短励志
12 图书馆简短祝福语
13 送教授贺卡祝福语简短
14 女孩结婚祝福语大全简短
15 社团迎新祝福语简短英语
16 兄弟生日恶搞祝福语简短
17 英文祝福语 唯美简短的
18 学校生日祝福语简短独特