这道题本质上就是大数相加,用string处理会很方便。分为整数部分和小数部分。先让小数和小数相加,以小数点对齐,加完把多余的零去掉,可能会有进位到整数的情况,如果有的话整数部分加一就行了。然后整数和整数相加,然后把整数和小数连接起来,输入的时候可能会有正整数,可以让正整数 +’.’+‘0’,变成小数。
#include<string>
#include<iostream>
using namespace std;
int flag;
string fun1(string s1, string s2) //小数相加代码
{
int len1 = s1.length();
int len2 = s2.length();
if (len1 > len2)
{
for (int i = 0; i < len1 - len2; i++)
{
s2 = s2 + '0';
}
}
else if (len1 < len2)
{
for (int i = 0; i < len2 - len1; i++)
{
s1 = s1 + '0';
}
}
int length_str = s1.length();
int c = 0;
int temp;
string ans;
for (int i = length_str-1; i >=0 ; i--)
{
temp = s1[i] - '0' + s2[i] - '0' + c;
c = temp / 10;
ans = char(temp % 10 + '0') + ans;
}
if (c)
{
flag = 1;
}
return ans;
}
string fun2(string s1, string s2) //整数相加代码
{
int len1 = s1.length();
int len2 = s2.length();
if (len1 > len2)
{
for (int i = 0; i < len1 - len2; i++)
{
s2 = '0' + s2 ;
}
}
else if (len1 < len2)
{
for (int i = 0; i < len2 - len1; i++)
{
s1 = '0' + s1;
}
}
int length_str = s1.length();
int c = flag;
int temp;
string ans;
for (int i = length_str - 1; i >= 0; i--)
{
temp = s1[i] - '0' + s2[i] - '0' + c;
c = temp / 10;
ans = char(temp % 10 + '0') + ans;
}
if (c)
{
ans = '1' + ans;
}
return ans;
}
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
if (s1.find('.') == s1.npos) //如果是整数,变成小数
{
s1 = s1 + '.'; s1 = s1 + '0';
}
if (s2.find('.') == s2.npos) //如果是整数,变成小数
{
s2 = s2 + '.'; s2 = s2 + '0';
}
flag = 0;
int index1, index2;
index1 = s1.find('.'); //以小数点为界,切割字符串
index2 = s2.find('.');
string s1_x = s1.substr(index1+1);
string s2_x = s2.substr(index2+1);
//cout << s1_x << " " << s2_x << endl;
string ans_x = fun1(s1_x, s2_x);
string s1_z = s1.substr(0, index1 );
string s2_z = s2.substr(0, index2 );
string ans_z = fun2(s1_z, s2_z);
//cout << s1_z << " " << s2_z << endl;
int find0 = -1;
for (int i = ans_x.length() - 1; i >= 0; i--)
{
if (ans_x[i] != '0')
{
find0 = i;
break;
}
}
ans_x = ans_x.substr(0, find0 + 1); //去掉多余的0
string res = ans_z; //把整数和小数连接
if (find0 != -1)
res = res + '.';
res = res + ans_x;
cout << res << endl;
}
return 0;
}