高精度计算
[cpp]
// 高精度加法
#include<iostream>
#include<cstring>
using namespace std;
int* strtoint(char *str)
{
int i,len=strlen(str);
int* a=new int[(len+1)*sizeof(int)];
for(i=0;i<len;i++)
a[i]=(int)str[len-i-1]-48;
return a;
}
char* inttostr(int* a,int n)
{
int i;
char* str=new char[(n+1)*sizeof(char)];
for(i=0;i<n;i++)
str[i]=(char)a[n-i-1]+48;
str[n]='\0';
return str;
}
int check(int* a,int n)
{
int k=0,len=n;
while(a[len-1]==0&&len>1)
len--;
for(k=0;k<len;k++)
if(a[k]>=10)
{
a[k+1]=a[k+1]+a[k]/10;
a[k]=a[k]%10;
}
if(a[k]!=0)
len=k+1;
return len;
}
char* addition(char* m1,char* m2)
{
int i,len1,len2,len,c=0;
int* t1,*t2;
len1=strlen(m1);
len2=strlen(m2);
len=(len1>=len2)?len1:len2;
t1=new int[(len+2)*sizeof(int)];
t2=new int[(len+2)*sizeof(int)];
t1=strtoint(m1);
t2=strtoint(m2);
for(i=len1;i<len+1;i++)
t1[i]=0;
for(i=len2;i<len+1;i++)
t2[i]=0;
for(i=0;i<len;i++)
t1[i]+=t2[i];
len=check(t1,len);
return inttostr(t1,len);
}
int main()
{
char m1[1000],m2[1000];
while(cin>>m1>>m2)
cout<<addition(m1,m2)<<endl;
return 0;
}
//高精度乘法
#include<iostream>
#include<cstring>
using namespace std;
int* strtoint(char* str)
{
int i,len;
len=strlen(str);
int* a=new int[(len+1)*sizeof(int)];
for(i=0;i<len;i++)
a[i]=(int)str[len-i-1]-48;
return a;
}
char* inttostr(int* a,int n)
{
char* str=new char[(n+1)*sizeof(int)];
for(int i=0;i<n;i++)
str[i]=(char)a[n-i-1]+48;
str[n]='\0';
return str;
}
int check(int* a,int n)
{
int k,len=n;
while(a[len-1]==0&&len>1)
len--;
for(k=0;k<len;k++)
{
a[k+1]+=a[k]/10;
a[k]%=10;
}
if(a[k]!=0)
len=k+1;
return len;
}
char* multiply(char* m1,char* m2)
{
int i,j,len1,len2,len,c=0,*t1,*t2,*prod;
len1=strlen(m1);
len2=strlen(m2);
len=len1+len2;
t1=new int[(len1+1)*sizeof(int)];
t2=new int[(len2+1)*sizeof(int)];
prod=new int[(len+1)*sizeof(int)];
t1=strtoint(m1);
t2=strtoint(m2);
for(i=0;i<len+1;i++)
prod[i]=0;
for(i=0;i<len1;i++)
for(j=0;j<len2;j++)
prod[i+j]+=t1[i]*t2[j];
len=check(prod,len);
return inttostr(prod,len);
}
int main()
{
char m1[1000],m2[1000];
while(cin>>m1>>m2)
cout<<multiply(m1,m2)<<endl;
return 0;
}
补充:软件开发 , C++ ,