大整数加法

#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; } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值