5.6 大整数运算 (乘法) A*B(注意负数的处理方法)

此方法适用于大整数乘以整数型。要特别注意负数的转换!

参考代码:

#include <cstdio>
#include <cstring>
struct bign{ //定义大整数结构体 
	int d[1000];
	int len;
	bign()
	{
		memset(d,0,sizeof(d));
		len=0;
	}
};
bign change(char str[])
{
	bign a;
	if(str[0]=='-') //去除'-'号 
	{
		a.len=strlen(str)-1;
		for(int i=0;i<a.len;++i)
		{
			a.d[i]=str[a.len-i]-'0'; //注意此处为-i,这样就不会枚举到第一位的符号位 
		}
	}
	else 
	{
		a.len=strlen(str);
		for(int i=0;i<a.len;++i)
		{
			a.d[i]=str[a.len-i-1]-'0'; //注意此处为-i-1.倒着存储,方便从低位至高位枚举 
		}
	}		
	return a;
}
bign multi(bign a,int b)
{
	bign c;
 	int temp,carry=0; //carry 为进位 
	for(int i=0;i<a.len;++i)
	{
		temp=a.d[i]*b+carry;
		c.d[c.len++]=temp%10;
		carry=temp/10;
	}
	while(carry!=0) //和加法不一样,乘法的进位可能不止一位 
	{
		c.d[c.len++]=carry;
		carry/=10;
	}
	return c;
}
void print (bign c)
{
	for(int i=c.len-1;i>=0;--i)
	{
		printf("%d",c.d[i]);
	}
	printf("\n");
}
char s1[1000];
int main()
{
	int b;
	while(scanf("%s%d",s1,&b)!=EOF)
	{
		bool flag=true; //记录正负号 
		if(s1[0]=='-')
			flag=!flag;
		if(b<0)
		{
			flag=!flag; 
			b=-b; //非常重要!不然会将负号代入乘法中,输出错误的结果。将负数转换为正数 
		}	
		bign a=change(s1);
		bign c=multi(a,b);
		if(!flag)
			printf("-");
		print(c); 
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值