题意:先输入一个整数Num表示计算的数据组数,再输入两个长整数num1和num2,最后要求输出num1+num2与num1-num2的值,当时有人建议我用链表来写,但最后我还是选择了简单一点的数组来写。
(这道水题唯二需要思考的点就是在运算时的进位Carry 与借位Borrow。)
1 #include <stdio.h> 2 #include <string.h> 3 4 #define MAX_SIZE 110 5 6 char n1[MAX_SIZE] = ""; 7 char n2[MAX_SIZE] = ""; 8 char n3[MAX_SIZE+1] = ""; 9 10 void Add(); 11 void Sub(); 12 13 int main() 14 { 15 int Num; 16 printf("请输入要计算的数据组数:\n"); 17 scanf("%d", &Num); 18 while(Num--) 19 { 20 printf("请输入要计算的第一个长整数num1:\n"); 21 scanf("%s", n1); 22 printf("请输入要计算的第二个长整数num2:\n"); 23 scanf("%s", n2); 24 Add(); 25 Sub(); 26 } 27 return 0; 28 } 29 30 void Add() 31 { 32 int L1; 33 int L2; 34 int Carry = 0; 35 int i = 0; 36 for(L1 = strlen(n1)-1, L2 = strlen(n2)-1; (L1 >= 0) && (L2 >= 0); L1--, L2--) 37 { 38 n3[i] = n1[L1] - '0' + n2[L2] - '0' + Carry; 39 Carry = n3[i] / 10; 40 n3[i] %= 10; 41 i++; 42 } 43 for(; L1 >= 0; L1--) 44 { 45 n3[i] = n1[L1] - '0' + Carry; 46 Carry = n3[i] / 10; 47 n3[i] %= 10; 48 i++; 49 } 50 for(; L2 >= 0; L2--) 51 { 52 n3[i] = n2[L2] - '0' + Carry; 53 Carry = n3[i] / 10; 54 n3[i] %= 10; 55 i++; 56 } 57 //printf("%d %d %d\n", n3[i-1],n1[0]- '0',i); 58 printf("num1+num2的值为:\n"); 59 //if(n3[i-1]<=n1[0]- '0')printf("1"); 60 if(Carry>0)printf("%d", Carry); 61 for(i=i-1; i >= 0; i--) 62 { 63 printf("%d", n3[i]); 64 } 65 printf("\n"); 66 } 67 68 void Sub() 69 { 70 int L1; 71 int L2; 72 int Borrow = 0; 73 int i = 0; 74 int sign = 0; 75 L1 = strlen(n1); 76 L2 = strlen(n2); 77 if ((L2 > L1) || (L2 == L1) && (strcmp(n2, n1) > 0)) 78 { 79 strcpy(n3, n1); 80 strcpy(n1, n2); 81 strcpy(n2, n3); 82 sign = -1; 83 } 84 for(L1 = strlen(n1)-1, L2 = strlen(n2)-1; (L1 >= 0) && (L2 >= 0); L1--, L2--) 85 { 86 n3[i] = n1[L1] - n2[L2] - Borrow; 87 Borrow = (n3[i] >= 0) ? 0 : 1; 88 if (n3[i] < 0) 89 { 90 n3[i] += 10; 91 } 92 i++; 93 } 94 for(; L1 >= 0; L1--) 95 { 96 n3[i] = n1[L1] - '0' - Borrow; 97 Borrow = (n3[i] >= 0) ? 0 : 1; 98 if (n3[i] < 0) 99 { 100 n3[i] += 10; 101 } 102 i++; 103 } 104 printf("num1-num2的值为:\n"); 105 if (sign == -1) 106 { 107 printf("-"); 108 } 109 int m; 110 m=0; 111 for(i=i-1; i > 0;i--) 112 { 113 if(n3[i]!=0) 114 { 115 m++; 116 } 117 118 if(n3[i]!=0||m!=0) 119 { 120 printf("%d", n3[i]); 121 } 122 123 } 124 printf("%d", n3[0]); 125 printf("\n"); 126 }