这个程序怎么写?
编写一个任意长整数的加减法,用字符串实现长整数的存放,每个元素一个数字。用C怎么写呢?求算法,求程序,求解释
[解决办法]
#include<stdio.h>#include<string.h>void reverseStr(char* str);int cmpStr(char* strA, char* strB);void main(){ char* strA,*strB,*strC,*strTemp; char oper; /*操作符*/ int m,n; int i,j,max,min,flag,neg=0; printf("length of first string: "); scanf("%d",&m); printf("length of second string: "); scanf("%d",&n); strA = (char*)malloc(m*sizeof(char)); strB = (char*)malloc(n*sizeof(char)); strC = (char*)malloc((m>n ? m+1 : n+1)*sizeof(char)); printf("input first string: "); scanf("%s",strA); printf("input second string: "); scanf("%s",strB); reverseStr(strA); reverseStr(strB); fflush(stdin); printf("input operator('+' or '-'): "); scanf("%c",&oper); switch(oper) { case '+': flag = 0; m = strlen(strA); n = strlen(strB); max = m>n ? m:n; for(i=0; i<max; i++) { strC[i] = flag + '0'; if(i<m) strC[i] += strA[i]- '0'; if(i<n) strC[i] += strB[i] - '0'; if(strC[i]-'0' > 9) { strC[i] = (strC[i]-'0')%10 + '0'; flag = 1; } else flag = 0; } strC[i] = '\0'; reverseStr(strC); printf("%s\n",strC); break; case '-': flag = 0; if(cmpStr(strA,strB)==0) { strC[i] = '0'; strC[i] = '\0'; printf("%s\n",strC); break; /*退出*/ } else if(cmpStr(strA,strB) < 0) { strTemp = strA; strA = strB; strB = strTemp; neg = -1; /*负数*/ } m = strlen(strA); n = strlen(strB); max = m>n ? m:n; for(i=0; i<max; i++) { strC[i] = flag + '0'; if(i<m) /* strA还有 */ strC[i] += strA[i] - '0'; if(i<n) strC[i] -= strB[i] - '0'; if(strC[i]-'0' < 0) { strC[i] = strC[i] + 10; flag = -1; /* 借位 */ } else flag = 0; } if(neg == -1) strC[i] = '-'; strC[i+1] = '\0'; reverseStr(strC); printf("%s\n",strC); break; }}/*把字符串反转*/void reverseStr(char* str){ char temp; int i; int n = strlen(str); for(i=0; i<n/2; i++) { temp = str[i]; str[i] = str[n-1-i]; str[n-1-i] = temp; }}/*比较字符串大小*/int cmpStr(char* strA, char* strB){ int i; if(strlen(strA) > strlen(strB)) return 1; /* A>B */ else if(strlen(strA) < strlen(strB)) return -1; /* A<B */ else { /* len(A) == len(B) */ for(i=0; i<strlen(strA); i++) { if(strA[i] > strB[i]) return 1; else return -1; } return 0; /* A=B */ }}