1 //加法器,若要变为减法器,只需改动相应的判断条件即可 2 #include <iostream> 3 using namespace std; 4 struct num//储存多位的整形数字 5 { 6 char input[102]; 7 char sign; 8 char data[101]; 9 int len; 10 }; 11 struct num plus_(struct num a, struct num b);//无符号整形的加法 12 struct num minus_(struct num a, struct num b);//无符号整形的减法,要求a>b 13 int main() 14 { 15 while (1)//while循环用作多次测试 16 { 17 struct num a, b, c;//a,b为加数,c储存二者相加结果 18 cin >> a.input; 19 cin >> b.input; 20 if (a.input[0] == '-')//把a和b的符号存起来,把去掉符号的数放到结构体的另一个数组里面 21 { 22 a.sign = '-'; 23 for (int i = 1; i <= strlen(a.input); i++) 24 { 25 a.data[i - 1] = a.input[i]; 26 } 27 } 28 else 29 { 30 a.sign = '+'; 31 for (int i = 0; i <= strlen(a.input); i++) 32 { 33 a.data[i] = a.input[i]; 34 } 35 } 36 if (b.input[0] == '-') 37 { 38 b.sign = '-'; 39 for (int i = 1; i <= strlen(b.input); i++) 40 { 41 b.data[i - 1] = b.input[i]; 42 } 43 } 44 else 45 { 46 b.sign = '+'; 47 for (int i = 0; i <= strlen(b.input); i++) 48 { 49 b.data[i] = b.input[i]; 50 } 51 } 52 //根据a,b符号的各种情况,调用plus_e和minus_函数进行运算 53 if (a.sign == '+' && b.sign == '+') 54 {//a,b为正数,直接相加 55 c = plus_(a, b); 56 const int len_ = strlen(c.data); 57 int i = 0; 58 for (i = 0; i < len_; i++) 59 { 60 if ((len_ - i) % 4 == 0 && i!=0) 61 cout << ','; 62 cout << c.data[i]; 63 } 64 cout << endl << "位数:" << strlen(a.data) << "," << strlen(b.data) << "," << i; 65 } 66 else if (a.sign == '-' && b.sign == '-') 67 {//a,b皆为负数,则a,b去掉负号后相加,在结果前添一个负号 68 c = plus_(a, b); 69 if (c.data[0] != 0) 70 cout << '-'; 71 int i = 0; 72 const int len_ = strlen(c.data); 73 for (i = 0; i < len_; i++) 74 { 75 if ((len_ - i) % 4 == 0 && i != 0) 76 cout << ','; 77 cout << c.data[i]; 78 } 79 cout << endl << "位数:" << strlen(a.data) << "," << strlen(b.data) << "," << i; 80 } 81 else 82 {//a,b一正一负,将a,b去掉负号后,用它们之间大的减去小的 83 int e_flag = 0;//a比b长(也即a>b)则为1,a比b短(即a<b)则为-1 84 int z_flag = 0;//结果为0标志 85 int la = strlen(a.data); 86 int lb = strlen(b.data); 87 if (la > lb)e_flag = 1; 88 else if (la < lb)e_flag = -1; 89 else//若a,b等长 90 {//下面判断它们的大小 91 for (int i = 0, j = 0; i < la, j < lb; i++, j++) 92 { 93 if (a.data[i] > b.data[j]) 94 { 95 e_flag = 1;//a>b 96 break; 97 } 98 else if (a.data[i] < b.data[j]) 99 { 100 e_flag = -1;//a<b 101 break; 102 } 103 } 104 } 105 if (e_flag == 1)//a>b,则c=a-b 106 { 107 c = minus_(a, b); 108 if (a.sign == '-' && b.sign == '+')//如果a负b正且a大于b,输出'-' 109 cout << '-'; 110 } 111 else if (e_flag == -1)//a<b,则c=b-a,结果前面添负号 112 { 113 c = minus_(b, a); 114 if (a.sign == '+' && b.sign == '-')//如果a正b负且b大于a,输出'-' 115 cout << '-'; 116 } 117 else//a,b相等的情况 118 { 119 c.data[0] = '0'; 120 c.data[1] = '