需要使用初学者逻辑创建C++二进制计算器
Need to create C++ Binary Calculator using beginner logic
我已经成功地设置了如何使用以下代码完成二进制加法,
#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 语句(如 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 << ". ";
}
}
}
这会将 1 分配给c
if (c = 1){
相比之下,c
比 1。
if (c == 1){
请为您的编译器打开警告。 你会被告知这样的错别字。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 使用std::multimap迭代器创建std::list
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 使用CMake创建QML插件
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 试图在visual studio上用C++创建一个桌面应用程序
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 如何在C++20中创建模板别名的推导指南
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 链接到自行创建的dll失败
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++类内存结构中创建"spacer"?
- 终端不会为C++文件创建.exe文件吗
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息