各位大牛,求助,求代码,题目如下:
程序达到的效果是:如果输入12极其34,屏幕输出46。给定条件如下a.仅需支持整数(包含整数和负数),不需支持浮点数。但整数的长度可以无限。
b.参数可以任意输出,参数不符合要求,输出错误提示。
#include "stdio.h" #include "string.h" #include "stdlib.h" #define CHK_NUM_RET(num) \ do{\ if(!((num) >= '0' && (num) <= '9')) \ {\ fprintf(stderr,"error, not number!\r\n");\ return 1;\ }\ }while(0) int main(int argc, char * argv[]) { char * pssum=NULL; int len1=0, len2=0, lensum=0; int num1=0, num2=0, sum=0, carry=0; int i=0; if(argc != 3) { fprintf(stderr, "Parameter error, need 2 numbers to sum\r\n"); return 1; } len1 = strlen(argv[1]); len2 = strlen(argv[2]); lensum = (len1 >= len2) ? len1 : len2; pssum = malloc(lensum); if(pssum == NULL) { fprintf(stderr, "no enough memory!\r\n"); return 2; } pssum[lensum] = '\0'; lensum--; len1--; len2--; carry=0; while(lensum>=0) { //get num1 if(len1 >= 0) { CHK_NUM_RET(argv[1][len1]); num1 = argv[1][len1] - '0'; } else num1=0; //get num2 if(len2 >= 0) { CHK_NUM_RET(argv[2][len2]); num2 = argv[2][len2] - '0'; } else num2=0; //get sum sum = num1+num2+carry; if(sum >= 10) { sum -= 10; carry=1; } else carry=0; pssum[lensum] = sum + '0'; lensum--; len1--; len2--; } if(carry == 1) { putchar('1'); } printf("%s\r\n", &pssum[0]); return 0; }