//将两个实数相加我们要将小数点前后分开存储
#include <iostream>
#include <cstring>
#include <vector>
//#include <bits/stdc++.h>
#include <stdio.h>
using namespace std;
int main() {
string a, b; //因为数太大我们用字符串存
vector<int>x, y, x1, y1;
vector<int>c, c1;
int n1 = 0, n = 0;
cin >> a >> b;
for (int i = 0; i < a.size(); i++) {
if (a[i] == '.') { //找到小数点出现的地方
n1 = 1;
continue;
}
if (n1 == 0)
x1.push_back(a[i] - '0'); //存整数部分
else
x.push_back(a[i] - '0'); //存小数部分
}
for (int i = 0; i < b.size(); i++) {
if (b[i] == '.') {
n = 1;
continue;
}
if (n == 0)
y1.push_back(b[i] - '0');
else {
// printf(" b[i]=%d", b[i]);
y.push_back(b[i] - '0');
}
}
// printf(" y=%d", y.size());
int m = 0, m1 = 0;
int max = 0, max1 = 0;
if (x.size() != y.size()) {
if (x.size() < y.size()) { //找到小数点后几位最小位第几位
max = y.size();
} else {
max = x.size();
}
} else {
max = y.size();
}
if (x1.size() != y1.size()) {
if (x1.size() < y1.size()) {
m = y1.size() - x1.size();
max1 = y1.size(); //找整数的最大位
} else {
m1 = x1.size() - y1.size();
max1 = x1.size();
}
} else {
max1 = x1.size();
}
int t = 0; //将t定义在外边 因为如果十分位相加大于10则个位要进一
// printf(" max=%d ", max);
// printf(" max1=%d ", max1);
for (int i = max - 1; i >= 0; i--) {
if (i < x.size()) //因为从后往前加这如果当前加到的位为零则不加,如0.122加0.123456 当加的小数点后第4为时 0.122的为0但我们并没有给他输入0,所以我们不加他
t += x[i];
if (i < y.size())
t += y[i];
// cout << t << endl;
c1.push_back(t % 10);
t = t / 10;
}
// cout << endl;
for (int i = max1 - 1, j = y1.size() - 1, w = x1.size() - 1; i >= 0; //如123加12345第万位相加是1+0;所以我们要判断实数的最大位是否大于等于它
i--, j--, w--) { //j,w分别用来判断两个数有没有到各自的最大位
if (w >= 0) //当w或j为0时则证明加到了他的最大位
t += x1[w];
// cout << t << endl;
if (j >= 0)
t += y1[j];
// cout << y1[i] << endl;
// cout << i << endl;
c.push_back(t % 10);
t = t / 10;
}
if (t) //如果t大于零则最大位相加加上进位数大于10我们要将它存下来 如68加73 十位为6+7+1=14则百位应给进个1;
c.push_back(t);
for (int i = c.size() - 1; i >= 0; i--) { // 输出整数
cout << c[i];
}
cout << ".";
for (int i = c1.size() - 1; i >= 0; i--) { //输出小数
cout << c1[i];
}
return 0;
// cout << endl;
}
实现 实数相加
于 2022-01-26 18:37:58 首次发布