1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 5 typedef struct bigInt { 6 char* num;//指向长整数数组,序号0中保存着最低位,也就是倒序存放 7 char minus;//符号,1表示正数,-1表示符数 8 int digit;//保存位数 9 }BigInt, *pBigInt; 10 11 void bigIntTrans(pBigInt num1);//将字符串转化成数字表示 12 void bigIntTrim(pBigInt num1);//整理大整数,去掉前面得0 13 void bigIntPrint(pBigInt result); 14 int bigIntEqual(pBigInt num1, pBigInt num2);//比较两个大整数大小 15 void bigIntAdd(pBigInt num1, pBigInt num2, pBigInt result); 16 void bigIntAdd1(pBigInt num1, pBigInt num2, pBigInt result);//同号相加 17 void bigIntSub1(pBigInt num1, pBigInt num2, pBigInt result);//用于异号相加 18 void bigIntSub(pBigInt num1, pBigInt num2, pBigInt result);//减法 19 void bigIntMul(pBigInt num1, pBigInt num2, pBigInt result);//乘法 20 void bigIntDiv(pBigInt num1, pBigInt num2, pBigInt result, pBigInt residue);//除法 21 22 int main(void) { 23 bigInt num1, num2, result, residue; 24 int i = 0, len; 25 char op; 26 27 printf("输入最大数的位数:"); 28 scanf("%d", &len); 29 if (!(num1.num = (char*)malloc(sizeof(char) * (len + 1)))) { printf("内存分配失败 "); exit(0); } 30 num1.digit = len + 1; 31 if (!(num2.num = (char*)malloc(sizeof(char) * (len + 1)))) { printf("内存分配失败 "); exit(0); } 32 num2.digit = len + 1; 33 if (!(result.num = (char*)malloc(sizeof(char) * (len + 1)))) { printf("内存分配失败 "); exit(0); } 34 result.digit = 2 * len + 1; 35 for (i = 0; i < result.digit; i++) result.num[i] = 0; 36 printf("选择大整数运算(+,-,*,/): "); 37 fflush(stdin);//刷新标准输入缓冲区,把输入缓冲区里的东西丢弃 38 scanf(" %c", &op); 39 switch (op) { 40 case '+': 41 printf(" 输入被加数:"); scanf("%s", num1.num); 42 printf(" 输入加数:"); scanf("%s", num2.num); 43 bigIntTrans(&num1); 44 bigIntTrans(&num2); 45 bigIntAdd(&num1, &num2, &result); 46 break; 47 case '-': 48 printf(" 输入被减数:"); scanf("%s", num1.num); 49 printf(" 输入减数:"); scanf("%s", num2.num); 50 bigIntTrans(&num1); 51 bigIntTrans(&num2); 52 bigIntSub(&num1, &num2, &result); 53 break; 54 case '*': 55 printf(" 输入被乘数:"); scanf("%s", num1.num); 56 printf(" 输入乘数:"); scanf("%s", num2.num); 57 bigIntTrans(&num1); 58 bigIntTrans(&num2); 59 bigIntMul(&num1, &num2, &result); 60 break; 61 case '/': 62 printf(" 输入被除数:"); scanf("%s", num1.num); 63 printf(" 输入除数:"); scanf("%s", num2.num); 64 bigIntTrans(&num1); 65 bigIntTrans(&num2); 66 if (num2.digit == 1 && num2.num[0] == '0') printf("除数不能为0! "); 67 else bigIntDiv(&num1, &num2, &result, &residue); 68 break; 69 } 70 71 if (op == '/') { 72 if (!(num2.digit == 1 && num2.num[0] == '0')) { 73 printf("商:"); bigIntPrint(&result); 74 printf(" 余数:"); bigIntPrint(&residue); 75 } 76 } 77 else {printf("结果:"); bigIntPrint(&result);} 78 79 80 return 0; 81 } 82 83 void bigIntTrans(pBigInt num1) { 84 char* t; 85 int i, k, len; 86 87 len = strlen(num1->num); 88 if (!(t = (char*)malloc(sizeof(char) * len))){printf("内存分配失败! ");exit(0); } 89 i = 0; 90 num1->minus = 1;//默认为正 91 if (num1->num[0] == '-') { num1->minus = -1; i++; }//若第一个字符试'-',那么则是负数 92 k = 0; 93 while (num1->num[i] != '