#include
#include
#include
#include
//#define _DEBUG_ void plus(char *, char *, char *); int is_valid(char *); void reverse(char*); int main(int argc, char *argv[]) { char up[81]; char down[81]; char line[163]; int loop; printf("请输入表达式(最长80位):如1+1/n"); scanf("%s", line); #ifdef _DEBUG_ printf("%s/n", line); #endif memset(up, 0, sizeof(up)); memset(down, 0, sizeof(down)); for(loop = 0; line[loop] != '+' && isalnum(line[loop]); loop++){ up[loop] = line[loop]; } up[loop] = '/0'; strcpy(down, line+loop+1); if (!is_valid(up) || !is_valid(down)){ printf("请输入正确表达式,如1+1”/n"); return -1; } plus(up, down, line); printf("结果为:%s/n", line); return 0; } /* * 判断字符串是否为合法数字表达式 */ int is_valid(char * str) { int loop; for(loop = 0; loop < strlen(str);loop++){ if(!isalnum(*str) || loop > 80) return 0; } return 1; } /* * 计算up字符串与down字符串的和,结果保存在result中 */ void plus(char *up, char *down, char *result) { int temp; int loop; int loopend; int sum; int res; memset(result, 0, sizeof(result)); #ifdef _DEBUG_ printf("down is %s,up is %s/n", up, down); #endif reverse(up); reverse(down); #ifdef _DEBUG_ printf("converse down is %s,converse up is %s/n", up, down); #endif if(strlen(up) > strlen(down)) loopend = strlen(up); else loopend = strlen(down); temp = 0; for(loop = 0; loop < loopend; loop++){ if(up[loop] == '/0') //处理短字符串 up[loop] = '0'; if(down[loop] =='/0') //处理短字符串 down[loop] = '0'; sum = up[loop] - '0' + down[loop] - '0' + temp; #ifdef _DEBUG_ printf("sum is %d/n", sum); #endif res = sum %10; //个位 result[loop] = res + '0'; temp = sum / 10; //进位 #ifdef _DEBUG_ printf("res is %d,temp is %d/n", res, temp); #endif } if (temp > 0) result[loop] = temp; else result[loop] = '/0'; if(++loop <= strlen(result)) result[loop] = '/0'; #ifdef _DEBUG_ printf("result is %s/n", result); #endif reverse(result); } /* * 翻转字符串 */ void reverse(char* str) { char temp; unsigned int len; char *end; len = strlen(str); end = str + len - 1; for(; str <= end; str++,end--){ if(*str == *end) continue; #ifdef _DEBUG_ printf("%c <==> %c/n", *str, *end); #endif temp = *str; *str = *end; *end = temp; } }
大整数加法
最新推荐文章于 2010-01-07 10:51:00 发布