编写程序,实现超过20位的无符号整数的加法和乘法运算。要求程序读入文本文件input.txt,计算其中的表达式的运算结果,并将结果输出到文本文件output.txt中。例如: 输入文件input.txt的内容 123456789012345678901234567890 + 123456789012345678901234567890 74795969103554554996215276693934490847811844274620 * 51 输出文件output.txt的内容 ( 123456789012345678901234567890 + 123456789012345678901234567890 = 246913578024691357802469135780 ) ( 74795969103554554996215276693934490847811844274620 * 51 = 3814594424281282304806979111390659033238404058005620 )(只能使用iostream,fstream,string数据库)
时间: 2024-01-22 12:17:24 浏览: 68
以下是使用iostream、fstream和string实现的代码:
```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string add(string s1, string s2) {
string result;
int carry = 0;
int i = s1.length() - 1;
int j = s2.length() - 1;
while (i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) {
sum += s1[i] - '0';
i--;
}
if (j >= 0) {
sum += s2[j] - '0';
j--;
}
carry = sum / 10;
sum %= 10;
result.insert(0, to_string(sum));
}
if (carry > 0) {
result.insert(0, to_string(carry));
}
return result;
}
string multiply(string s1, int n) {
string result;
int carry = 0;
for (int i = s1.length() - 1; i >= 0; i--) {
int product = (s1[i] - '0') * n + carry;
carry = product / 10;
product %= 10;
result.insert(0, to_string(product));
}
if (carry > 0) {
result.insert(0, to_string(carry));
}
return result;
}
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
string s1, s2;
char op;
while (fin >> s1 >> op >> s2) {
if (op == '+') {
string result = add(s1, s2);
fout << "(" << s1 << " + " << s2 << " = " << result << ")" << endl;
}
else if (op == '*') {
int n = stoi(s2);
string result = multiply(s1, n);
fout << "(" << s1 << " * " << s2 << " = " << result << ")" << endl;
}
}
fin.close();
fout.close();
return 0;
}
```
程序首先打开输入文件input.txt和输出文件output.txt,然后读入每一行表达式,通过调用add函数实现加法运算,通过调用multiply函数实现乘法运算,并将结果写入输出文件中。最后关闭文件并返回0。
阅读全文