Problem Description
读入两个字符串,字符串除了数字还可能包括 '—'、'E'、'e'、'.',相加之后输出结果,如果是浮点型,要求用科学计数法表示(最多包含10个有效数字)。
Input Description
输入包含多组测试数据。
每组输入占两行,每行一个字符串,测试数据保证字符串的构成严格按照题目中的描述。
Output Description
输出两个数字相加的结果,每组输出占一行。
Sample Input
34.56 2.45e2Sample Output
2.7956e2
#include <iostream>
#include <string.h>
using namespace std;
char str1[100];//存储数组
char str2[100];
void In(char str[], long long *s, int *a)
{
*s = 0;
*a = 0;
int leng;
leng = strlen(str);
int flag = 0;//记录正负号
int point = 0;//看是否有小数点
int e = 0;// 记录e后面的次方数
for (int i = 0; i < leng; i++)
{
if (str[i] == '-')
{
flag = 1;
}
else if (str[i] == '.')
{
point = 1;
}
else if (str[i] == 'e' || str[i] == 'E')
{
sscanf(str + i + 1, "%d", &e);
*a = *a + e;
break;
}
else
{
*s = *s * 10 + (str[i] - '0');
*a = *a - point;
}
}
if (flag)//如果为负数
{
*s = -*s;
}
}
int main()
{
int length1, length2;//存储两个数组长度
int flag = 0;//判断是否为负正为0负为1
int point = 0;//判断是否有小数点
int a1, a2, e, a, w;
long long s1, s2, s, ans;
while (scanf("%s %s", str1, str2) != EOF)
{
In(str1, &s1, &a1);
In(str2, &s2, &a2);
//cout << "a1 = " << a1 << " " << "a2 = " << a2 << endl;
if (a1 < a2)//str2的小数位数比str1多
{
while (a1 < a2)
{
s2 = s2 * 10;
a2--;
}
}
else if (a1 > a2)
{
while (a1 > a2)
{
s1 = s1 * 10;
a1--;
}
}
//cout << "a1 = " << a1 << " " << "a2 = " << a2 << endl;
//printf("%lld, %lld\n", s1, s2);
a = a1; //此时a1应该等于a2
s = s1 + s2; //两数之和
if (!s)//相加为0
{
printf("0\n");
continue;
}
while (a < 0 && s % 10 == 0)//e后面的次方是负的
{
s = s / 10;
a++;
}
//cout << "s = " << s << " " << "a = " << a << endl;
if (a >= 0)//e后面的次方是正的
{
printf("%lld", s);
for (int i = 0; i < a; i++)
{
printf("0");
}
printf("\n");
continue;
}
flag = 0;
if (s < 0)
{
s = -s;
flag = 1;
}
ans = 1, w = 0;
while (ans <= s)
{
ans = ans * 10;
w++;
}
//cout << "ans = " << ans << " " << "w = " << w << endl;
if (ans > 1)
{
ans = ans / 10;
w--;
}
//cout << "ans = " << ans << " " << "w = " << w << endl;
if (flag)
{
printf("-");
}
printf("%lld", s / ans);
if (ans > 1)
{
printf(".%lld", s % ans);
}
printf("e%d\n", a + w);
}
return 0;
}