只用STRING類實現支持任意數的高精度運算
时间: 2024-03-03 13:53:46 浏览: 17
好的,以下是一个使用STRING类实现高精度运算的示例代码,支持任意数的加法、减法和乘法运算:
```
#include <iostream>
#include <string>
using namespace std;
string add(string num1, string num2) {
int carry = 0;
string result = "";
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
while (num2.length() < num1.length()) {
num2 = "0" + num2;
}
for (int i = num1.length() - 1; i >= 0; i--) {
int sum = (num1[i] - '0') + (num2[i] - '0') + carry;
carry = sum / 10;
result = to_string(sum % 10) + result;
}
if (carry > 0) {
result = to_string(carry) + result;
}
return result;
}
string subtract(string num1, string num2) {
int borrow = 0;
string result = "";
while (num1.length() < num2.length()) {
num1 = "0" + num1;
}
while (num2.length() < num1.length()) {
num2 = "0" + num2;
}
for (int i = num1.length() - 1; i >= 0; i--) {
int diff = (num1[i] - '0') - (num2[i] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result = to_string(diff) + result;
}
while (result.length() > 1 && result[0] == '0') {
result = result.substr(1);
}
return result;
}
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
int len1 = num1.length(), len2 = num2.length();
string result(len1 + len2, '0');
for (int i = len1 - 1; i >= 0; i--) {
int carry = 0;
for (int j = len2 - 1; j >= 0; j--) {
int sum = (num1[i] - '0') * (num2[j] - '0') + (result[i + j + 1] - '0') + carry;
carry = sum / 10;
result[i + j + 1] = to_string(sum % 10)[0];
}
result[i] += carry;
}
while (result.length() > 1 && result[0] == '0') {
result = result.substr(1);
}
return result;
}
int main() {
string num1, num2;
cout << "Please input two numbers: " << endl;
cin >> num1 >> num2;
cout << "Result of addition: " << add(num1, num2) << endl;
cout << "Result of subtraction: " << subtract(num1, num2) << endl;
cout << "Result of multiplication: " << multiply(num1, num2) << endl;
return 0;
}
```
这段代码中使用了STRING类的基本操作,实现了任意数的高精度加法、减法和乘法运算。您可以根据需要进行修改和扩展。