D盘num.txt
96994554545234233543543534545435534343456435232324234234
789789789789323920248249357535235435443654634543643
源程序:
#include <iostream.h>
#include<stdio.h>
#include<stdlib.h>
#define LENGTH 100 //定义数最长长度
int main()
{
int num1[LENGTH];
int num2[LENGTH];
int result[LENGTH];
int i,TEMP1,TEMP2,TEMP3,max;
static int LENGTH1=0,LENGTH2=0;
FILE *p;
char ch;
result[0]=0;
for(i=0;i<LENGTH;i++) //数组初始化
{
num1[i]=0;
num2[i]=0;
result[i]=0;
}
i=0;
if((p=fopen("D://num.txt","r"))==NULL) //打开文件
{
cout<<"can't open the file"<<endl;
exit(0);
}
ch=fgetc(p);
while(ch!=10) //获取数1
{
num1[i]=ch-48;
i++;
LENGTH1++;
ch=fgetc(p);
}
i=0;
ch=fgetc(p);
while(ch!=EOF) //获取数2
{
num2[i]=ch-48;
i++;
LENGTH2++;
ch=fgetc(p);
}
TEMP1=LENGTH1-1;
TEMP2=LENGTH2-1;
max=LENGTH1>LENGTH2?LENGTH1:LENGTH2;
max++;
if(LENGTH1>=LENGTH2) //数1大于数2
{
TEMP3=LENGTH1;
for(i=TEMP2;i>=0;i--)
{
result[TEMP3--]+=num1[TEMP1--]+num2[TEMP2--]; //数相加
if(result[TEMP3+1]>9)
{
result[TEMP3+1]-=10; //大于9进1
result[TEMP3]+=1;
}
}
for(i=LENGTH1-LENGTH2-1;i>=0;i--) //补高位
{
result[i+1]+=num1[i];
if(result[i+1]>9)
{
result[i+1]-=10;
result[i]+=1;
}
}
}
else //数1小于数2
{
TEMP3=LENGTH2;
for(i=TEMP1;i>=0;i--)
{
result[TEMP3--]+=num1[TEMP1--]+num2[TEMP2--];
if(result[TEMP3+1]>9)
{
result[TEMP3+1]-=10;
result[TEMP3]+=1;
}
}
for(i=LENGTH2-LENGTH1-1;i>=0;i--)
{
result[i+1]+=num2[i];
if(result[i+1]>9)
{
result[i+1]-=10;
result[i]+=1;
}
}
}
for(i=0;i<max;i++) //输出数1
{
if(i<max-LENGTH1)
{
cout<<" ";
}
else
{
cout<<num1[i-max+LENGTH1];
}
}
cout<<endl<<"+"<<endl;
for(i=0;i<max;i++) //输出数2
{
if(i<max-LENGTH2)
{
cout<<" ";
}
else
{
cout<<num2[i-max+LENGTH2];
}
}
cout<<endl<<"="<<endl;
for(i=0;i<max;i++) //输出结果
{
cout<<result[i];
}
cout<<endl;
fclose(p);
return 0;
}
输出: