C++的无符号整数类型表示范围有限,能表示的十进制无符号整数不超过20位。编写程序,实现超过20位的无符号整数的加法和乘法运算。要求程序读入文本文件input.txt,计算其中的表达式的运算结果,并将结果输出到文本文件output.txt中。例如: 输入文件input.txt的内容 123456789012345678901234567890 + 123456789012345678901234567890 74795969103554554996215276693934490847811844274620 * 51 输出文件output.txt的内容 ( 123456789012345678901234567890 + 123456789012345678901234567890 = 246913578024691357802469135780 ) ( 74795969103554554996215276693934490847811844274620 * 51 = 3814594424281282304806979111390659033238404058005620 )
时间: 2024-01-21 21:20:13 浏览: 102
uint128_t:C ++无符号128位整数类型
以下是C++的实现代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> add(vector<int>& a, vector<int>& b) {
vector<int> res;
int carry = 0;
int i = a.size() - 1, j = b.size() - 1;
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) sum += a[i--];
if (j >= 0) sum += b[j--];
res.push_back(sum % 10);
carry = sum / 10;
}
if (carry) res.push_back(carry);
reverse(res.begin(), res.end());
return res;
}
vector<int> multiply(vector<int>& a, int b) {
vector<int> res;
int carry = 0;
for (int i = a.size() - 1; i >= 0; i--) {
int prod = a[i] * b + carry;
res.push_back(prod % 10);
carry = prod / 10;
}
if (carry) res.push_back(carry);
reverse(res.begin(), res.end());
return res;
}
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
string s1, s2;
fin >> s1 >> s2;
vector<int> a, b;
for (int i = s1.size() - 1; i >= 0; i--) a.push_back(s1[i] - '0');
for (int i = s2.size() - 1; i >= 0; i--) b.push_back(s2[i] - '0');
vector<int> res_add = add(a, b);
vector<int> res_mul = multiply(a, stoi(s2));
fout << "(" << s1 << " + " << s2 << " = ";
for (int i = 0; i < res_add.size(); i++) fout << res_add[i];
fout << ")" << endl;
fout << "(" << s1 << " * " << s2 << " = ";
for (int i = 0; i < res_mul.size(); i++) fout << res_mul[i];
fout << ")" << endl;
fin.close();
fout.close();
return 0;
}
```
程序首先读入两个字符串s1和s2,分别表示要相加和相乘的两个数。然后将它们转化为vector<int>类型,方便进行加法和乘法操作。接下来调用add和multiply函数进行相应的操作,最后将结果输出到文件output.txt中。
阅读全文