不知道哪个老六想出来的高精度计算
2023-08-13 11:04:10
发布于:江苏
5阅读
0回复
0点赞
Hola,大家好,我是那个德布劳内说是神犇的哈兰德。这个程序使用了一个vector<int>来存储大整数的每一位数字,然后手动模拟竖式计算,将两个大整数相加,并将结果存储在另一个vector<int>中。最后将结果转换为字符串输出。下面是代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 大数加法
string add(string a, string b) {
vector<int> a_digits, b_digits;
// 将两个字符串转换为数字数组
for (int i = a.size() - 1; i >= 0; i--) {
a_digits.push_back(a[i] - '0');
}
for (int i = b.size() - 1; i >= 0; i--) {
b_digits.push_back(b[i] - '0');
}
// 手动模拟竖式计算
vector<int> result_digits;
int carry = 0;
int i = 0, j = 0;
while (i < a_digits.size() || j < b_digits.size()) {
int x = (i < a_digits.size()) ? a_digits[i++] : 0;
int y = (j < b_digits.size()) ? b_digits[j++] : 0;
int sum = x + y + carry;
result_digits.push_back(sum % 10);
carry = sum / 10;
}
if (carry != 0) {
result_digits.push_back(carry);
}
// 将结果转换为字符串并反转
string result;
for (int i = result_digits.size() - 1; i >= 0; i--) {
result += to_string(result_digits[i]);
}
return result;
}
int main() {
int a, b;
cin >> a >> b;
cout << a+b << endl; //没想到吧!
return 0;
}
啊呸,给老子正经一点
下面是正确代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 大数加法
string add(string a, string b) {
vector<int> a_digits, b_digits;
// 将两个字符串转换为数字数组
for (int i = a.size() - 1; i >= 0; i--) {
a_digits.push_back(a[i] - '0');
}
for (int i = b.size() - 1; i >= 0; i--) {
b_digits.push_back(b[i] - '0');
}
// 手动模拟竖式计算
vector<int> result_digits;
int carry = 0;
int i = 0, j = 0;
while (i < a_digits.size() || j < b_digits.size()) {
int x = (i < a_digits.size()) ? a_digits[i++] : 0;
int y = (j < b_digits.size()) ? b_digits[j++] : 0;
int sum = x + y + carry;
result_digits.push_back(sum % 10);
carry = sum / 10;
}
if (carry != 0) {
result_digits.push_back(carry);
}
// 将结果转换为字符串并反转
string result;
for (int i = result_digits.size() - 1; i >= 0; i--) {
result += to_string(result_digits[i]);
}
return result;
}
int main() {
string a, b;
cin >> a >> b;
cout << add(a, b) << endl;
return 0;
}
这里空空如也
有帮助,赞一个