一. 问题提出

C语言中，整型变量所能存储的最宽数据为0xFFFF FFFF，对应的无符号数为4294967295，即无法保存超过10位的整数。注意，此处"10位"指数学中的10个数字，并非计算机科学中的10比特。浮点类型double虽然可以存储更多位数的整数，但一方面常数字面量宽度受编译器限制，另一方面通过浮点方式处理整数精度较低。例如：

    double a = 1377083362513770833626.0, b=1585054852315850548524.0;
printf("res = %.0f\n", a+b);


二. 代码实现

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

#define MUL_THRES     (sizeof("65535")-2)       //两个4位整数相乘不会溢出
#define OTH_THRES     (sizeof("4294967295")-1)  //两个10位整数相减或相除不会溢出

typedef struct{
char *leftVal;
char *rightVal;
char operator;
}MATH_OPER;


void Addition(char *leftVal,  char *rightVal,
char *resBuf, unsigned int resbufLen) {
unsigned int leftLen = strlen(leftVal);
unsigned int rightLen = strlen(rightVal);

unsigned char isLeftLonger = (leftLen>=rightLen) ? 1 : 0;
unsigned int longLen = isLeftLonger ? leftLen : rightLen;
if(resbufLen < longLen) { //possible carry + string terminator
fprintf(stderr, "Not enough space for result(cur:%u)!\n", resbufLen);
return;
}

char *longAddend = isLeftLonger ? leftVal : rightVal;
char *shortAddend = isLeftLonger ? rightVal : leftVal;
unsigned int diffLen = isLeftLonger ? (leftLen-rightLen) : (rightLen-leftLen);
//a carry might be generated from adding the most significant digit
if((leftLen == rightLen) && (leftVal[0]-'0'+rightVal[0]-'0' >= 9))
resBuf += 1;

unsigned int carry = 0;
int i = longLen-1;
for(; i >= 0; i--) {
resBuf[i] = digitSum % 10 + '0';
carry = (digitSum >= 10) ? 1 : 0;
}
if(carry == 1) {
resBuf -= 1;
resBuf[0] = '1';
}
else if(leftVal[0]-'0'+rightVal[0]-'0' == 9) {
resBuf -= 1;
resBuf[0] = ' '; //fail to generate a carry
}
}


void Subtraction(char *leftVal,  char *rightVal,
char *resBuf, unsigned int resbufLen) {
int cmpVal = strcmp(leftVal, rightVal);
if(!cmpVal) {
resBuf[0] = '0';
return;
}

unsigned int leftLen = strlen(leftVal);
unsigned int rightLen = strlen(rightVal);
unsigned char isLeftLonger = 0;
if((leftLen > rightLen) ||              //100-10
(leftLen == rightLen && cmpVal > 0)) //100-101
isLeftLonger = 1;
unsigned int longLen = isLeftLonger ? leftLen : rightLen;
if(resbufLen <= longLen) { //string terminator
fprintf(stderr, "Not enough space for result(cur:%u)!\n", resbufLen);
return;
}

char *minuend = isLeftLonger ? leftVal : rightVal;
char *subtrahend = isLeftLonger ? rightVal : leftVal;
unsigned int diffLen = isLeftLonger ? (leftLen-rightLen) : (rightLen-leftLen);
//a borrow will be generated from subtracting the most significant digit
if(!isLeftLonger) {
resBuf[0] = '-';
resBuf += 1;
}

unsigned int borrow = 0;
int i = longLen-1;
for(; i >= 0; i--)
{
unsigned int expanSubtrahend = (i<diffLen) ? '0' : subtrahend[i-diffLen];
int digitDif = minuend[i] - expanSubtrahend - borrow;
borrow = (digitDif < 0) ? 1 : 0;
resBuf[i] = digitDif + borrow*10 + '0';
//printf("[%d]Dif=%d=%c-%c-%d -> %c\n", i, digitDif, minuend[i], expanSubtrahend, borrow, resBuf[i]);
}

int iSrc = 0, iDst = 0, isStripped = 0;
while(resBuf[iSrc] !='\0') {
if(isStripped) {
resBuf[iDst] = resBuf[iSrc];
iSrc++; iDst++;
}
else if(resBuf[iSrc] != '0') {
resBuf[iDst] = resBuf[iSrc];
iSrc++; iDst++;
isStripped = 1;
}
else
iSrc++;
}
resBuf[iDst] = '\0';
}


#include<assert.h>
char resBuf[100] = {0}; \
assert(!strcmp(resBuf, _sum)); \
}while(0)
#define ASSERT_SUB(_minu, _subt, _dif) do{\
char resBuf[100] = {0}; \
Subtraction(_minu, _subt, resBuf, sizeof(resBuf)); \
assert(!strcmp(resBuf, _dif)); \
}while(0)
void VerifyOperation(void) {

ASSERT_SUB("10012345678890", "1", "10012345678889");
ASSERT_SUB("1", "10012345678890", "-10012345678889");
ASSERT_SUB("10012345678890", "10012345678891", "-1");
ASSERT_SUB("10012345678890", "10012345686945", "-8055");
ASSERT_SUB("1000000000000", "999999999999", "1");
}


void CalcOperation(MATH_OPER *mathOper, char *resBuf, unsigned int resbufLen) {
unsigned int leftLen = strlen(mathOper->leftVal);
unsigned int rightLen = strlen(mathOper->rightVal);

switch(mathOper->operator) {
case '+':
snprintf(resBuf, resbufLen, "%d",
atoi(mathOper->leftVal) + atoi(mathOper->rightVal));
else
break;
case '-':
if(leftLen <= OTH_THRES && rightLen <= OTH_THRES)
snprintf(resBuf, resbufLen, "%d",
atoi(mathOper->leftVal) - atoi(mathOper->rightVal));
else
Subtraction(mathOper->leftVal, mathOper->rightVal, resBuf, resbufLen);
break;
case '*':
if(leftLen <= MUL_THRES && rightLen <= MUL_THRES)
snprintf(resBuf, resbufLen, "%d",
atoi(mathOper->leftVal) * atoi(mathOper->rightVal));
else
break; //Multiplication: product = multiplier * multiplicand
break;
case '/':
if(leftLen <= OTH_THRES && rightLen <= OTH_THRES)
snprintf(resBuf, resbufLen, "%d",
atoi(mathOper->leftVal) / atoi(mathOper->rightVal));
else
break; //Division: quotient = dividend / divisor
break;
default:
break;
}

return;
}


int main(void) {
VerifyOperation();

char leftVal[100] = {0}, rightVal[100] = {0}, operator='+';
char resBuf[1000] = {0};

//As you see, basically any key can quit:)
printf("Enter math expression(press q to quit): ");
while(scanf(" %[0-9] %[+-*/] %[0-9]", leftVal, &operator, rightVal) == 3) {
MATH_OPER mathOper = {leftVal, rightVal, operator};
memset(resBuf, 0, sizeof(resBuf));
CalcOperation(&mathOper, resBuf, sizeof(resBuf));
printf("%s %c %s = %s\n", leftVal, operator, rightVal, resBuf);
printf("Enter math expression(press q to quit): ");
}
return 0;
}


三. 效果验证

[wangxiaoyuan_@localhost ~]$gcc -Wall -o BigIntOper BigIntOper.c [wangxiaoyuan_@localhost ~]$ ./BigIntOper
Enter math expression(press q to quit): 100+901
100 + 901 = 1001
Enter math expression(press q to quit): 100-9
100 - 9 = 91
Enter math expression(press q to quit): 1234567890123 + 8867901223000
1234567890123 + 8867901223000 = 10102469113123
Enter math expression(press q to quit): 1377083362513770833626 - 1585054852315850548524
1377083362513770833626 - 1585054852315850548524 = -207971489802079714898
Enter math expression(press q to quit): q
[wangxiaoyuan_@localhost ~]\$


posted @ 2016-06-22 15:37  clover_toeic  阅读(9917)  评论(0编辑  收藏  举报