#include<stdio.h>
#include<stdlib.h>
typedef struct bit
{
int num;
struct bit *next;
}BIT;
/*
创建节点
参数n:节点对应的数值
返回所对应的节点
*/
BIT *creatNode(int n)
{
BIT *p=(BIT *)malloc(sizeof(BIT));
p->num=n;
p->next=NULL;
return p;
}
/*
第i位乘数与被乘数的计算
参数head:结果链表的头指针;str:被乘数串;ch:乘数第i位的数值:i:乘数位数
*/
void multi(BIT *head,char *str,char ch,int i)
{
BIT *ptr,*q;
char *p;
int nu11,nu12,a1=0,a2=0,n=0;//*a1被乘数位与乘数位相乘产生的进位
//a2:与结果链相应累加产生的进位
ptr=head;
while(n<i)
{
if(ptr->next!=NULL)
ptr=ptr->next;
else
{
q=creatNode(0);
ptr->next=q;
ptr=ptr->next;
}
n++;
}
p=str;
while(*p!='\0')p++;
q=ptr;
while(p>str)
{
p--;
nu11=(*p-'0')*(ch-'0')+a1; //乘运算
a1=nu11/10;
nu11%=10; //a1为乘数进位
if(ptr==NULL)
{
ptr=creatNode(0);
q->next=ptr;
q=ptr;
}
nu12=ptr->num+nu11+a2;//与结果连当前位累加
a2=nu12/10; //a2为累加进位
nu12%=10; //本次运算最终值
ptr->num=nu12;
q=ptr;
ptr=ptr->next;
}
if(a1!=0||a2!=0) //处理最高进位
{
if(ptr==NULL)
{
ptr=creatNode(0);
q->next=ptr;
}
ptr->num=ptr->num+a1+a2;
}
}
void multiply(BIT **head,char *str1,char *str2)//str1被乘数,str2乘数
{
char *p;
int i;
p=str2;//定位乘数个数
while(*p!='\0')p++;//为str2的每一位分配空间
*head=creatNode(0);
i=0;
while(p>str2)
{
p--;
if(*p!='0'){
multi(*head,str1,*p,i);}//乘数的第i位*p乘以被乘数
i++;
}
}
void Printf(BIT *h)//打印结果,参数h:结果头子针
{
if(h==NULL)
return;
if(h->next!=NULL)
Printf(h->next);
printf("%d",h->num);
}
main()
{
char str1[30],str2[30];
BIT *head;
int i=0;
printf("请输入被乘数:");
scanf("%s",str1);
printf("请输入乘数:");
scanf("%s",str2);
multiply(&head,str1,str2);
Printf(head);
return 0;
}
大数相乘
最新推荐文章于 2025-06-29 16:32:06 发布