瓦库的什么茶好喝:刚学c++,高手帮帮忙啊!!
来源:百度文库 编辑:高校问答 时间:2024/08/27 00:54:01
用链表做的小程序:
//计算多位数加法
#include<iostream.h>
struct number
{
int digit;
number* before;
};
int main()
{
cout<<"请输入两个数:";
char s;
int c1=0,c2=0;
number* num1=NULL,* num2=NULL,*temp;
num1=new number;
num1->before=NULL;
num1->digit=0;
while(s=cin.get(),s>='0'&&s<='9') //输入数字
{
c1++;
temp=new number;
temp->before=num1;
num1=temp;
num1->digit=s-'0';
}
num2=new number;
num2->before=NULL;
num2->digit=0;
while(s=cin.get(),s>='0'&&s<='9')
{
c2++;
temp=new number;
temp->before=num2;
num2=temp;
num2->digit=s-'0';
}
int count=0; //加和
number *result=c1>c2?num1:num2,* head1=result,* head2=c1>c2?num2:num1;
while(1)
{
count+=num1->digit+num2->digit;
result->digit=count%10;
count=count/10;
num1=num1->before;
num2=num2->before;
result=result->before;
if(num1==NULL||num2==NULL)
break;
}
result=NULL;
delete result;
do{ //释放部分内存
number *temp;
temp=head2;
head2=head2->before;
delete temp;
}while(head2);
number *s1=head1->before,*s2=NULL; //将链表转置,以便输出
head1->before=NULL;
while(s1->before)
{
s2=s1->before;
s1->before=head1;
head1=s1;
s1=s2;
}
cout<<"结果是: "; //输出
while(head1)
{
cout<<head1->digit;
number *temp=head1;
head1=head1->before;
delete temp;
}
cout<<endl;
return 1;
}
用数组50个应该够了
数组每个数记录一个位的数字
用循环a[0]+b[0]
考虑进位
如果是实现多个数字相加,可以用下面程序:
#include "iostream.h"
int main(){
int result = 0;
int t;
cout<<"输入要相加的加数,可以多个,输入-1结束"<<endl;
cin>>t;
while(t!=-1) {
result += t;
cin>>t;
}
cout<<"Result is: "<<result<<endl;
return 0;
}
如果题目不是要求多个数字相加,而是要求相加的数有无限多位,那就可以用数组存储了,或者是直接用字符串存储,从低位起取出一个字符,对应相加,并转化,考虑进位即可。
实现很简单。