题 C++的无符号整数类型表示范围有限,能表示的十进制无符号整数不超过 20位。编写程序,实现超过 20 位的无符号整数的加法和乘法运算。 要求程序读入文本文件 input. txt,计算其中的表达式的运算结果,并将结果输出到文本文件 output.txt 中
时间: 2023-12-14 15:39:11 浏览: 71
实现超过20位的无符号整数加法和乘法运算可以使用字符串来存储数字,然后模拟手算的方式进行运算。
以下是一份参考代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
string add(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int Alen = a.size(), Blen = b.size();
string res = "";
int carry = 0;
for (int i = 0; i < max(Alen, Blen); i++) {
int x = i < Alen ? a[i] - '0' : 0;
int y = i < Blen ? b[i] - '0' : 0;
int sum = x + y + carry;
res += (char)(sum % 10 + '0');
carry = sum / 10;
}
if (carry > 0) {
res += (char)(carry + '0');
}
reverse(res.begin(), res.end());
return res;
}
string multiply(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int Alen = a.size(), Blen = b.size();
string res(Alen + Blen, '0');
for (int i = 0; i < Alen; i++) {
int carry = 0;
int x = a[i] - '0';
for (int j = 0; j < Blen; j++) {
int y = b[j] - '0';
int product = x * y + carry + (res[i + j] - '0');
res[i + j] = (char)(product % 10 + '0');
carry = product / 10;
}
if (carry > 0) {
res[i + Blen] += carry;
}
}
reverse(res.begin(), res.end());
while (res.size() > 1 && res[0] == '0') {
res.erase(0, 1);
}
return res;
}
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
string line;
while (getline(fin, line)) {
string a, b;
char op;
int i = 0;
while (line[i] >= '0' && line[i] <= '9') {
a += line[i];
i++;
}
op = line[i];
i++;
while (i < line.size() && line[i] >= '0' && line[i] <= '9') {
b += line[i];
i++;
}
if (op == '+') {
fout << add(a, b) << endl;
} else if (op == '*') {
fout << multiply(a, b) << endl;
}
}
fin.close();
fout.close();
return 0;
}
```
代码中使用了 `add` 函数和 `multiply` 函数来分别实现加法和乘法。这两个函数的实现都是通过将数字字符串反转后模拟手算的方式来实现的。在 `multiply` 函数中,还需要在每次计算乘积时,将当前位置的值加上之前已经计算出来的值,以支持多位数的乘法。
在主函数中,我们读取输入文件中的每一行,解析出其中的操作数和操作符,并调用相应的函数计算结果并输出到输出文件中。
阅读全文
相关推荐
















