//输入A,执行长整数加法
//输入B,执行长整数减法
#include<stdio.h>
#include<string.h>
int main()
{
void sum(int x[],int y[]); //加法函数
void sub(int x[],int y[]); //减法函数
char c1[80],c2[80];
char c;
int i,a1[80]={0},a2[80]={0};
printf("Please put tow numbers:\n");
gets(c1);
gets(c2);
printf("Put A will carry out addition.\nPut B will carry out submit.\n");
scanf("%c",&c);
a1[0]=strlen(c1);
a2[0]=strlen(c2);
for(i=a1[0];i>=1;i--){
a1[a1[0]-i+1]=c1[i-1]-48; //a1逆序赋值 ,便于计算
}
for(i=a2[0];i>=1;i--){
a2[a2[0]-i+1]=c2[i-1]-48; //a2逆序赋值 ,便于计算
}
switch(c)
{
case'A':sum(a1,a2);break; //输入A,执行加法
case'B':sub(a1,a2);break; //输入B,执行减法
}
return 0;
}
//加法函数
void sum(int x[],int y[])
{
int i,s;
if(x[0]>=y[0]){ //前者位数大于等于后者
for(i=1;i<y[0]+1;i++){
s=x[i]+y[i];
if(s>=0&&s<=9){
x[i]=s;
}
else{
x[i]=s%10;
x[i+1]=x[i+1]+1;
}
}
if(x[x[0]+1]!=0){ //增加1位数
for(i=x[0]+1;i>=1;i--){
printf("%d",x[i]);
}
}
else
{
for(i=x[0];i>=1;i--){ //逆序输出
printf("%d",x[i]);
}
}
}
else{ //前者位数小于后者
for(i=1;i<x[0]+1;i++){
s=x[i]+y[i];
if(s>=0&&s<=9){
y[i]=s;
}
else{
y[i]=s%10;
y[i+1]=y[i+1]+1;
}
}
if(y[y[0]+1]!=0){ //增加1位数
for(i=y[0]+1;i>=1;i--){
printf("%d",y[i]);
}
}
else
{
for(i=y[0];i>=1;i--){ //逆序输出
printf("%d",y[i]);
}
}
}
}
//减法函数
void sub(int x[],int y[])
{
int i,k=0,s;
if((x[0]>y[0])||(x[0]==y[0]&&x[x[0]]>y[y[0]])) //无需考虑负数,前者位数大于等于后者..或者前者后者位数相等且
//前者最后一位数大于后者最后一位数,(就是前者数值大于后者的意思)
{
for(i=1;i<y[0]+1;i++){
s=x[i]-y[i];
if(s>=0&&s<=9){
x[i]=s;
}
else{
x[i]=10+s;
x[i+1]=x[i+1]-1;
}
}
for(i=x[0];i>=1;i--){
if(x[i]!=0)
break;
else k+=1;
}
if(k==x[0]){ //两数完全相等
printf("0");
}
else{
for(i=x[0]-k;i>=1;i--){ //逆序输出
printf("%d",x[i]);
}
}
}
else
{
for(i=1;i<x[0]+1;i++){ //前者小于后者
s=y[i]-x[i];
if(s>=0&&s<=9){
y[i]=s;
}
else{
y[i]=10+s;
y[i+1]=y[i+1]-1;
}
}
for(i=y[0];i>=1;i--){
if(y[i]!=0)
break;
else k+=1;
}
if(k==y[0]){
printf("0");
}
else{
printf("-");
for(i=y[0]-k;i>=1;i--){ //逆序输出
printf("%d",y[i]);
}
}
}
}
附上流程图:
三个函数
主函数
加法函数
减法函数