运用C++写了一个大整数相加的bigInt.h的头文件,同时对该引用类型进行了加法,赋值运算符的重载,所以直接引用头文件就可以了。不用了解各个函数。效率也挺不错的。哦还有,输出用 bigInt.output();。
不过需要注意的是这是我为了求斐波那契所写的,所以并没有实现 以字符串为参数的构造函数,只实现了以int 为参数的构造函数,所以初始构造不能超过10位的整数,否则会溢出。
原理就是竖位相加,将一个整数倒序放在整形数组里,然后进行相加,不过因为数据成员里有数组,所以需要重写拷贝构造函数。okay,上代码
bigint.h
#include<memory.h>
#include<iostream>
using namespace std;
class bigInt
{
public:
bigInt(int );
bigInt();
bigInt( const bigInt &copied);
virtual ~bigInt();
int *data;
int length;
bigInt operator +(bigInt &b);
bigInt & operator =(bigInt b);
void output();
};
#endif // BIGINT_H
h2>bigInt.cpp
#include "bigInt.h"
bigInt::bigInt()//无参构造
{
data=new int[100];
length=0;
}
bigInt::bigInt(const bigInt & copied)//拷贝构造
{
data=new int[100];
for(int i=0;i<copied.length;i++)
{
data[i]=copied.data[i];
}
length=copied.length;
}
bigInt::bigInt(int number)//整数构造
{
data=new int[100];
int i=0;
while(number!=0){
data[i]=number%10;
number/=10;
i++;
}
length=i;//数的位数
}
bigInt::~bigInt()
{
}
bigInt bigInt:: operator +(bigInt &b)//加法运算符重载
{
bigInt result;
int i=0;
int j=0;
int extra=0;//进位
int e=0;//记录结果的位数
while(i<this->length&&j<b.length){
result.data[e]=(this->data[i]+b.data[j]+extra)%10;
extra=(this->data[i]+b.data[j]+extra)/10;
i++;j++;e++;
}
while(i<this->length){
result.data[e]=(this->data[i]+extra)%10;
extra=(this->data[i]+extra)/10;
i++;e++;
}
while(j<b.length){
result.data[e]=(b.data[j]+extra)%10;
extra=(b.data[j]+extra)/10;
j++;e++;
}
if(extra!=0)
{
result.data[e]=1;
e++;
}
result.length=e;
return result;
}
void bigInt::output()//输出函数
{
int i=length-1;
while(i>=0){
cout<<data[i];
i--;
}
}
bigInt & bigInt::operator =(bigInt b)//赋值运算符重载
{
this->length=b.length;
int i;
for(i=0;i<b.length;i++)
{
this->data[i]=b.data[i];
}
return *this;
}
求斐波那契,循环求
#include <iostream>
#include<ctime>
#include"bigInt.h"
using namespace std;
int main()
{
clock_t startTime2,endTime2;
int target;
cout<<"please input the number to calculate:";
cin>>target;
bigInt pre(1) ,last(1),temp;
startTime2=clock();//第二次计时开始
if(target==1||target==2){
}
else{
for(int i=3;i<=target;i++)
{
temp=pre+last;
pre=last;
last=temp;
}
}
endTime2=clock();
cout<<"循环结果:";
last.output();
cout<<endl;
cout<<"循环时间:"<<(double)(endTime2-startTime2)/CLOCKS_PER_SEC<<"s"<<endl;
}