模拟不同进制的加减法C++
时间: 2023-07-11 16:32:30 浏览: 53
好的,可以的。关于不同进制的加减法,我们可以使用 C++ 编写一个程序来实现。下面是一个简单的示例代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// 将字符串表示的数字转化为对应的十进制数
int toDecimal(string num, int base) {
int res = 0;
for (int i = 0; i < num.size(); ++i) {
int digit = (isdigit(num[i])) ? (num[i] - '0') : (num[i] - 'A' + 10);
res = res * base + digit;
}
return res;
}
// 将十进制数转化为对应的字符串表示
string fromDecimal(int num, int base) {
string res = "";
while (num) {
int digit = num % base;
res += (digit < 10) ? (digit + '0') : (digit - 10 + 'A');
num /= base;
}
reverse(res.begin(), res.end());
return res;
}
// 对两个字符串表示的数字进行加法运算
string add(string num1, string num2, int base) {
int carry = 0, sum = 0;
string res = "";
while (!num1.empty() || !num2.empty() || carry) {
int digit1 = (!num1.empty()) ? toDecimal(string(1, num1.back()), base) : 0;
int digit2 = (!num2.empty()) ? toDecimal(string(1, num2.back()), base) : 0;
sum = digit1 + digit2 + carry;
carry = sum / base;
sum %= base;
res += fromDecimal(sum, base);
if (!num1.empty()) num1.pop_back();
if (!num2.empty()) num2.pop_back();
}
reverse(res.begin(), res.end());
return res;
}
// 对两个字符串表示的数字进行减法运算
string subtract(string num1, string num2, int base) {
int borrow = 0, diff = 0;
string res = "";
while (!num1.empty() || !num2.empty()) {
int digit1 = (!num1.empty()) ? toDecimal(string(1, num1.back()), base) : 0;
int digit2 = (!num2.empty()) ? toDecimal(string(1, num2.back()), base) : 0;
diff = digit1 - digit2 - borrow;
borrow = 0;
if (diff < 0) {
diff += base;
borrow = 1;
}
res += fromDecimal(diff, base);
if (!num1.empty()) num1.pop_back();
if (!num2.empty()) num2.pop_back();
}
reverse(res.begin(), res.end());
return res;
}
int main() {
string num1, num2;
int base;
char op;
cin >> num1 >> op >> num2 >> base;
if (op == '+') cout << add(num1, num2, base) << endl;
else if (op == '-') cout << subtract(num1, num2, base) << endl;
return 0;
}
```
在程序中,我们首先定义了三个函数:`toDecimal`、`fromDecimal` 和 `add`、`subtract`,分别用于将字符串表示的数字转化为对应的十进制数、将十进制数转化为对应的字符串表示、对两个字符串表示的数字进行加法运算、对两个字符串表示的数字进行减法运算。
在 `main` 函数中,我们首先读取两个字符串表示的数字 `num1` 和 `num2`,以及运算符 `op` 和进制数 `base`。然后根据运算符 `op` 来调用 `add` 或 `subtract` 函数进行加减法运算,并输出结果。
需要注意的是,在进行加减法运算时,我们需要先将字符串表示的数字转化为对应的十进制数,然后再进行运算,最后再将运算结果转化为对应的字符串表示。这里我们使用 `toDecimal` 和 `fromDecimal` 函数来完成这个转换过程,其中 `toDecimal` 函数将字符串表示的数字转化为十进制数,`fromDecimal` 函数将十进制数转化为字符串表示。