高精度计算

高精度加法

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<cmath>
#include<time.h>
using namespace std;
int main()
{
	string s1,s2;
	cin>>s1>>s2;
	int t;
	if (s1.length()>s2.length())
		t=s1.length();
	else
		t=s2.length();

	int a[t],b[t],c[t];
	memset(a,0,sizeof(a));
	memset(b,0,sizeof(b));
	memset(c,0,sizeof(c));
	int p=0;
	for (int i = s1.length(); i > 0; i--)
	{
		a[p]=s1[i-1]-'0';
		p++;		
	}
	p=0;
	for (int i = s2.length(); i > 0; i--)
	{
		b[p]=s2[i-1]-'0';
		p++;
	}

	for (int i = 0; i < t; i++)
	{
		c[i+1]=(a[i]+b[i])/10;
		c[i]+=(a[i]+b[i])%10;
		printf("c[%d]=%d\n", i, c[i]);
	}
	check:
	for (int i = 0; i < t; i++)
	{
		if (c[i]>=10)
		{
			c[i+1]+=c[i]/10;
			c[i]=c[i]%10;
		}
	}
	if (c[t]!=0)
		printf("%d", c[t]);
	for (int i = t-1; i >= 0; i--)
		printf("%d", c[i]);
	return 0;
}

CC BY-SA 4.0 高精度计算 by 小小泥娃的部落格 is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

高精度计算》上有3条评论

发表评论