#include <iostream>
#include <string>
#include <algorithm>
#include <stdio.h>
using namespace std;
int part_carrier;
struct Float {
string num_int;
string num_part;
Float(string &num_int, string &num_part) :
num_int(num_int), num_part(num_part) {};
Float() {};
};
Float getFloat(string &str) {
int ix = str.find('.');
string num1_int, num1_part;
//第一个整数处理
if (ix == string::npos) {// 说明没有小数部分
num1_int = str;
num1_part = "";
} else {
num1_int = str.substr(0, ix);
num1_part = str.substr(ix + 1);
}
return Float(num1_int, num1_part);
}
string getpart(string &part1, string &part2) {
//这个和整数运算是有区别的
if (part1.size() < part2.size()) {
swap(part1, part2);
}
int carrier = 0;
string res;
for (int i = part2.size() - 1; i >= 0; --i) {
int n = (part1[i] - '0') + (part2[i] - '0') + carrier;
carrier = n / 10;
n = n % 10;
res.push_back(n + '0');
}
part_carrier = carrier;
for (int i = part2.size(); i < part1.size(); ++i) {
res.insert(0, 1, part1[i]);
}
//为了保证同意,反转
reverse(res.begin(), res.end());
return res;
}
string getint(string &num1, string &num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
if (num1.size() < num2.size()) {
swap(num1, num2);
}
string res;
int carrier = part_carrier;
for (int i = 0; i < num2.size(); ++i) {
int n = (num1[i] - '0') + (num2[i] - '0') + carrier;
carrier = n / 10;
n = n % 10;
res.push_back(n + '0');
}
for (int i = num2.size(); i < num1.size(); ++i) {
int n = (num1[i] - '0') + carrier;
carrier = n / 10;
n = n % 10;
res.push_back(n + '0');
}
if (carrier != 0) {
res.push_back(carrier + '0');
}
part_carrier = 0;
return res;
}
int main() {
// freopen("../in.txt", "r", stdin);
string num1, num2;
while (cin >> num1 >> num2) {
//小数部分和整数部分分开计算
Float aFloat = getFloat(num1);
Float bFloat = getFloat(num2);
//先计算小数部分
Float res;
if (aFloat.num_part == "") {
res.num_part = bFloat.num_part;
} else if (bFloat.num_part == "") {
res.num_part = aFloat.num_part;
} else {
res.num_part = getpart(aFloat.num_part, bFloat.num_part);
}
//小数部分结束
res.num_int = getint(aFloat.num_int, bFloat.num_int);
//整数部分和小数部分都算完,准备打印
//整数部分
for (int i = res.num_int.size()-1; i >= 0; --i) {
cout<<res.num_int[i];
}
int len = res.num_part.size()-1;
while (len>=0&&res.num_part[len]=='0'){
len--;
}
if (len>=0){
cout<<".";
for (int i = 0; i <= len; ++i) {
cout<<res.num_part[i];
}
}
cout<<endl;
}
}
浮点数的大数问题
最新推荐文章于 2022-10-17 13:20:18 发布