大数相乘

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#define N 100

int main()
{
	int i,j;
	bool flag = false;
	char s1[N],s2[N];
	printf("输入被乘数:\n");
	scanf("%s",s1);
	printf("输入乘数:\n");
	scanf("%s",s2);
	int len1 = strlen(s1);
	int len2 = strlen(s2);
	int len = len1 + len2 + 1;
	char *a = (char*)malloc(len1*sizeof(char));
	char *b = (char*)malloc(len2*sizeof(char));
	char *c = (char*)malloc(len*sizeof(char));
	for(i=0;i<len;i++)
		c[i]=0;
	for(i=0;i<len1;i++)//倒置
		a[i] = s1[len1-1-i] - '0';
	for(i=0;i<len2;i++)
		b[i] = s2[len2-1-i] - '0';
	for(i=0;i<len1;i++)//各位相乘
		for(j=0;j<len2;j++)
			c[i+j] += a[i]*b[j];
	for(i=0;i<len;i++)//进位
		if(c[i] > 9)
		{
			c[i+1] += c[i]/10;
			c[i] %= 10;
		}
	printf("结果为:\n");
	for(i=len-1;i>=0;i--)
	{
		if(flag)
		{
			c[i] += '0';
			printf("%c",c[i]);
		}
		else if(c[i] != 0)//判断最高位是不是0
		{
			c[i] += '0';
			printf("%c",c[i]);
			flag = true;
		}
	}
	printf("\n");
	free(a);
	free(b);
	free(c);
	a = NULL;
	b = NULL;
	c = NULL;
	return 0;
}

你可能感兴趣的:(大数相乘)