优化后的代码如下:

#include<stdio.h> #include<stdlib.h>

#define MaxSize 100

typedef struct {
long data[MaxSize]; long top; }SqStack;

void InitStack(SqStack *&s)//初始化栈 { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; }

bool Push(SqStack *&s,int e)//入栈 { if(s->top==MaxSize-1) return false; s->top++; s->data[s->top]=e; return true; }

bool Pop(SqStack *&s,int &e)//出栈 { if(s->top==-1) return false; e=s->data[s->top]; s->top--; return true; }

void putin(SqStack *&s,char *c)//输入整数 { for(;*c!='\0';c++) if(*c!=',') Push(s,*c-'0'); }

void DispStack(SqStack *s)//输出整数 { int j=0; int i=0; for(i=0;i<(s->top+1)%4;i++) printf("%d",s->data[i]); for(;i<=s->top;i++) { if(i!=0) { if(j%4==0) { printf(","); } } j++; printf("%d",s->data[i]); } }

int compare(SqStack *&s1,SqStack *&s2) { if(s1->top>s2->top) return 1; if(s1->toptop) return -1; if(s1->top==s2->top) { for(int i=0;i<=s1->top;i++) { if(s1->data[i]>s2->data[i]) return 1; if(s1->data[i]data[i]) return -1; } return 0; } }

SqStack * sum(SqStack *&s1,SqStack *&s2) { int i,j; SqStack *a,*b; InitStack(a); InitStack(b); for(i=s1->top,j=s2->top;i>=0&&j>=0;i--,j--) { Push(a,s1->data[i]+s2->data[j]); } for(;j>=0;j--) Push(a,s2->data[j]); for(;i>=0;i--) Push(a,s1->data[i]); for(i=0;itop;i++)//进位 { if(a->data[i]>=10) { a->data[i]-=10; a->data[i+1]+=1; } } if(a->data[a->top]>=10) { a->data[a->top]-=10; Push(a,1); } InitStack(b); for(i=a->top;i>=0;i--)//反序 Push(b,a->data[i]); return b; }

SqStack * Deduct(SqStack *&s1,SqStack *&s2) { int i,j; SqStack *a,*b; if(compare(s1,s2)==0) { InitStack(b); Push(b,0); return b; } InitStack(a); if(compare(s1,s2)==1) { for(i=s1->top,j=s2->top;j>=0;i--,j--) { Push(a,s1->data[i]-s2->data[j]); } for(;i>=0;i--) Push(a,s1->data[i]); for(i=0;i<=a->top;i++)//借位 { if(a->data[i]<0) { a->data[i]+=10; a->data[i+1]-=1; } } while(a->data[a->top]==0) a->top--; } if(compare(s1,s2)==-1) { for(i=s1->top,j=s2->top;i>=0;i--,j--) { Push(a,s2->data[j]-s1->data[i]); } for(;j>=0;j--) Push(a,s2->data[j]); for(i=0;i<=a->top;i++)//借位 { if(a->data[i]<0) { a->data[i]+=10; a->data[i+1]-=1; } }
while(a->data[a->top]==0) a->top--; a->data[a->top]=-a->data[a->top]; } InitStack(b); for(i=a->top;i>=0;i--)//反序 Push(b,a->data[i]); return b; }

int main() { SqStack *a,*b,*t; char *c=(char )malloc(100sizeof(char)); InitStack(a); InitStack(b); printf("num 1:"); scanf("%s",c); putin(a,c); printf("num 2:"); scanf("%s",c); putin(b,c); t=sum(a,b); printf("加法:\n"); DispStack(a); printf("+"); DispStack(b); printf("="); DispStack(t); t=Deduct(a,b); printf("\n减法:\n"); DispStack(a); printf("-"); DispStack(b); printf("="); DispStack(t); printf("\n"); system("pause"); }


原文地址: https://www.cveoy.top/t/topic/bzbq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录