c++ - 二进制计算器减法
问题描述
我目前正在为我的学校做一个关于二进制数的项目。我已经制作了一个可以正常工作的加法计算器,现在我正在尝试制作一个用于减法的计算器。我面临一些问题。最大的一个是我得到负数作为输出,当我使用时我binary 2's complement
没有得到任何负结果,但它们仍然是错误的。示例:当110010
用 (30) 减去 (50) 时,11110
我的输出10-1-100
不是10100
. 在第二补码中转换 30 时,(00010)
我的输出是110000
十进制的 48
这是代码:
#include <iostream>
using namespace std;
int main() {
long a, b;
int i = 0, r = 0, sub[20];
cout << "1st number: ";
cin >> a;
cout << "2nd number: ";
cin >> b;
while (a != 0 || b != 0)
{
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 << "Difference: ";
while (i >= 0)
cout << sub[i--];
cout << ". ";
system("pause");
return 0;
}
提前致谢
解决方案
关于减法,我可以看到您只是在逐位比较数字,如果第一个数字中的一个0
位是,第二个数字中的相应位是1
,它就可以了0 - 1 = -1
,而不考虑其他数字的数量。
添加一个在当前数字为负数时更改其他数字的条件应该可以解决问题:
#include <iostream>
using namespace std;
int main() {
long a, b;
int i = 0, r = 0, sub[20];
cout << "1st number: ";
cin >> a;
cout << "2nd number: ";
cin >> b;
while (a != 0 || b != 0)
{
sub[i] = (a % 10 - b % 10 + r) % 2; //Change the "i++" and put "i".
r = (a % 10 - b % 10 + r) / 2;
//Add this:
while(sub[i - 1] < 0)
{
sub[i-1] += 2;
sub[i]--;
}
//Until here
a = a / 10;
b = b / 10;
i++; //Increment "i" here.
}
if (r != 0)
sub[i++] = r;
--i;
//Add this if you want to ignore the leading 0's:
while (i >= 1 && sub[i] == 0)
i--;
//Until here.
cout << "Difference: ";
while (i >= 0)
cout << sub[i--];
cout << ". ";
system("pause");
return 0;
}
关于在第二补码中转换数字。输入应该是怎样的?
推荐阅读
- python - 无法识别使用硒“点击”下一页的内容
- javascript - Discord.js 创建带有服务器信息的 JSON 文件
- integer-overflow - 为什么我的程序的输出是秘密的值?
- javascript - 访问 HTMLRewriter 中的嵌套元素 - Cloudflare Workers
- javascript - 如何使用反应类组件创建 algolia 自动完成自定义渲染器
- angular - PrimeNg 组织结构图:删除选定节点
- arrays - 将对象数组转换为 csv
- javascript - Javascript:使用 x-www-form 在对象中获取和发布数组
- dbeaver - DBeaver 转储和还原 GENERATED 列的问题
- python - Pandas:使用元组作为标签从唯一的行值对创建列