我已成功设置了如何使用以下代码完成二进制加法,
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
long a, b;
int i = 0, r = 0, sum[20];
cout << "Enter the first binary number: ";
cin >> a;
cout << "Enter the second binary number: ";
cin >> b;
while (a != 0 || b != 0)
{
sum[i++] = (a % 10 + b % 10 + r) % 2;
r = (a % 10 + b % 10 + r) / 2;
a = a / 10;
b = b / 10;
}
if (r != 0)
sum[i++] = r;
--i;
cout << "The sum of the two binary numbers is: ";
while (i >= 0)
cout << sum[i--];
cout << ". ";
system("pause");
return 0;
}
我需要使用类似的方法来允许二进制减法和乘法。我尝试了以下代码,但它没有按计划运行。添加if语句(如果c = 1)会导致循环继续多次,从不给出正确的答案。单独使用减法公式,给出与添加相同的结果。有人可以帮我解决这个问题吗?感谢
#include <stdio.h>
#include <iostream>
using namespace std;
int main() {
long a, b;
int c = 0;
cout << "Enter the first binary number: ";
cin >> a;
cout << "Enter the second binary number: ";
cin >> b;
cout << "Which operation do you want to complete: Add=1, Subtract=2, Multiply=3: ";
cin >> c;
if (c = 1){
while (a != 0 || b != 0)
{
int i = 0, r = 0, sum[20];
sum[i++] = (a % 10 + b % 10 + r) % 2;
r = (a % 10 + b % 10 + r) / 2;
a = a / 10;
b = b / 10;
}
if (r != 0)
sum[i++] = r;
--i;
cout << "The sum of the two binary numbers is: ";
while (i >= 0)
cout << sum[i--];
cout << ". ";
}
if (c = 2) {
while (a != 0 || b != 0)
{
int i = 0, r = 0, sub[20];
sub[i++] = (a % 10 - b % 10 + r) % 2;
r = (a % 10 - b % 10 + r) / 2;
a = a / 10;
b = b / 10;
if (r != 0)
sub[i++] = r;
--i;
cout << "The difference of the two binary numbers is: ";
while (i >= 0)
cout << sub[i--];
cout << ". ";
}
if (c = 3) {
while (a != 0 || b != 0)
{
int i = 0, r = 0, prod[20];
prod[i++] = (a % 10 * b % 10 + r) % 2;
r = (a % 10 * b % 10 + r) / 2;
a = a / 10;
b = b / 10;
if (r != 0)
prod[i++] = r;
--i;
cout << "The product of the two binary numbers is: ";
while (i >= 0)
cout << prod[i--];
cout << ". ";
}
}
}
答案 0 :(得分:1)
此指定 1到c
if (c = 1){
将 c
与1进行比较。
if (c == 1){
请打开编译器的警告。你会被告知像这样的拼写错误。