您的位置:首页 > 其它

两个数相乘,小数点后位数没有限制

2012-11-04 09:46 417 查看
算法提示:

输入 string a, string b; 计算string c=a*b; 返回 c;

1, 纪录小数点在a,b中的位置l1,l2, 则需要小数点后移动位置数为l=length(a)+length(b)-l1-l2-2;

2, 去掉a,b中的小数点,(a,b小数点后移,使a,b变为整数)

3, 计算c=a*b; (同整数的大数相乘算法)

4, 输出c,(注意在输出倒数第l个数时,输出一个小数点。若是输出的数少于l个,就补0)

du51(郁郁思扬)的答案:

变为整数求就行了.输入的时候记一下,小数点位置..输出再做点文章就行了.

下面的是大整数的运算.

#include<iostream>

using namespace std;

#define MAX 10000

struct Node{

int data;

Node *next;

};

void output(Node *head)

{

if(!head->next&&!head->data)return;

output(head->next);

cout<<head->data;

}

void Mul(char *a,char *b,int pos)

{

char *ap=a,*bp=b;

Node *head=0;

head=new Node;head->data=0,head->next=0; //头

Node *p,*q=head,*p1;

int temp=0,temp1,bbit;

while(*bp) //若乘数不为空 ,继续.

{

p=q->next;p1=q;

bbit=*bp-48; //把当前位转为整型

while(*ap||temp) //若被乘数不空,继续

{

if(!p) //若要操作的结点为空,申请之

{

p=new Node;

p->data=0;

p->next=0;

p1->next=p;

}

if(*ap==0)temp1=temp;

else { temp1=(p1->data)+(*ap-48)*bbit+temp;ap++; }

p1->data=temp1%10; //留当前位

temp=temp1/10; //进位以int的形式留下.

p1=p;p=p->next; //被乘数到下一位

}

ap=a;bp++;q=q->next; //q进下一位

}

p=head;

output(p); //显示

cout<<endl;

while(head) //释放空间

{

p=head->next;

delete head;

head=p;

}

}

int main()

{

cout<<"请输入两个数"<<endl;

char test1[MAX],test2[MAX];

cin.getline(test1,MAX,'\n');

cin.getline(test2,MAX,'\n');

Mul(strrev(test1),strrev(test2));

system("PAUSE");

return 0;

}

上面大整数已经写了.你加几个东西就行了.

#include<iostream>

using namespace std;

#define MAX 10000

struct Node{

int data;

Node *next;

};

void output(Node *head,int pos)

{

if(!head->next&&!head->data)return;

output(head->next,pos-1);

cout<<head->data;

if(!pos)cout<<".";

}

void Mul(char *a,char *b,int pos)

{

char *ap=a,*bp=b;

Node *head=0;

head=new Node;head->data=0,head->next=0; //头

Node *p,*q=head,*p1;

int temp=0,temp1,bbit;

while(*bp) //若乘数不为空 ,继续.

{

p=q->next;p1=q;

bbit=*bp-48; //把当前位转为整型

while(*ap||temp) //若被乘数不空,继续

{

if(!p) //若要操作的结点为空,申请之

{

p=new Node;

p->data=0;

p->next=0;

p1->next=p;

}

if(*ap==0)temp1=temp;

else { temp1=(p1->data)+(*ap-48)*bbit+temp;ap++; }

p1->data=temp1%10; //留当前位

temp=temp1/10; //进位以int的形式留下.

p1=p;p=p->next; //被乘数到下一位

}

ap=a;bp++;q=q->next; //q进下一位

}

p=head;

output(p,pos); //显示

cout<<endl;

while(head) //释放空间

{

p=head->next;

delete head;

head=p;

}

}

int main()

{

cout<<"请输入两个数"<<endl;

char test1[MAX],test2[MAX],*p;

int pos=0;

cin.getline(test1,MAX,'\n');

cin.getline(test2,MAX,'\n');

if(p=strchr(test1,'.'))

{

pos+=strlen(test1)-(p-test1)-1;

do

{

p++;

*(p-1)=*p;

}while(*p);

}

if(p=strchr(test2,'.'))

{

pos+=strlen(test2)-(p-test2)-1;

do

{

p++;

*(p-1)=*p;

}while(*p);

}

Mul(strrev(test1),strrev(test2),pos);

system("PAUSE");

return 0;

}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hanlin1985/archive/2008/10/10/3048605.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: