HDU 1753 大明A+B

/*
高精度专题做完了,全部AC,开心。。。

题意:输入两个小数a、b,输出它们相加之和

思路:
第一步:将小数转化成整数
第二部:对小数位数比较小的那一位进行补零操作
第三步:相加,然后输出即可
①处曾经出错
*/
#include <cstdio>
#include <cstring>
const int nMax = 407;
struct BigNumber
{
	int data[nMax];
	int len;
	BigNumber(){len = 1; memset(data, 0 ,sizeof(data));}
	BigNumber(char *str){*this = str;}
	BigNumber & operator=(char *str);
	BigNumber operator+(BigNumber &a);
	void clearLeadZero();
};
BigNumber & BigNumber::operator =(char *str)
{
	memset(data, 0, sizeof(data));
	len = strlen(str);
	int i;
	for(i = 0; i < len; ++ i)
		data[i] = str[len - i - 1] - '0';
	return *this;
}
BigNumber BigNumber::operator +(BigNumber &a)
{
	BigNumber z;
	int q = 0;
	int i, j;
	for(i = 0, j = 0; q || i < len || j < a.len; ++ i, ++ j)
	{
		int p = data[i] + a.data[j] + q;
		z.data[i] = p % 10;
		q = p / 10;
	}
	z.len = i;
	z.clearLeadZero();
	return z;
}
void BigNumber::clearLeadZero()
{
	while(len > 1 && !data[len - 1]) -- len;
}
char A[nMax], B[nMax];
void solve()
{
	//寻找小数点
	int a_point = -1,
		b_point = -1;
	int a_len = strlen(A),
		b_len = strlen(B);
	int i;
	for(i = 0; i < a_len; ++ i)
	{
		if(A[i] == '.') a_point = a_len - i - 1;
		if(a_point != -1)
			A[i] = A[i + 1];
	}
	for(i = 0; i < b_len; ++ i)
	{
		if(B[i] == '.') b_point = b_len - i - 1;
		if(b_point != -1)
			B[i] = B[i + 1];
	}
	a_len = strlen(A);//①这里曾经出错
	b_len = strlen(B);
	if(-1 == a_point) a_point = 0;
	if(-1 == b_point) b_point = 0;
	//补零
	int point;
	if(a_point > b_point)
	{
		for(i = 0; i < a_point - b_point; ++ i)
			B[b_len + i] = '0';
		B[b_len + i] = 0;
		point = a_point;
	}
	else
	{
		for(i = 0; i < b_point - a_point; ++ i)
			A[a_len + i] = '0';
		A[a_len + i] = 0;
		point = b_point;
	}
	//相加
	BigNumber a = A;
	BigNumber b = B;
	a = a + b;
	//尾部零的省略
	int j = 0;
	while(!a.data[j]) ++j;
	if(a.len >= point)
	{
		if(j >= point)
		{
			for(i = a.len - 1; i >= point; -- i)
				printf("%d", a.data[i]);
		}
		else
		{
			for(i = a.len - 1; i >= point; -- i)
				printf("%d", a.data[i]);
			printf(".");
			for(i = point - 1; i >= j; -- i)
				printf("%d", a.data[i]);
		}
	}
	else
	{
		printf(".");
		for(i = point - 1; i >= a.len; -- i)
			printf("0");
		for(; i >= j; -- i)
			printf("%d", a.data[i]);
	}
	if(a.len == j && a.len == point)
		printf("0");
	printf("\n");
}
int main()
{
	//freopen("f://data.in", "r", stdin);
	while(scanf("%s%s", A, B) != EOF)
	{
		solve();
	}
	return 0;
}

你可能感兴趣的:(struct)