普通的大数运算

只写了加减,乘除不太明白T_T..弄明白补上。

  1 #include <stdio.h>
2 #include <string.h>
3
4 #define MAX 1000
5
6 void Add(char *str1,char *str2, char *str3);
7 void Minus(char *str1, char *str2, char *str3);
8 void Times(char *str1, char *str2, char *str3);
9
10 int main(void)
11 {
12 char str1[MAX], str2[MAX], str3[MAX+10];
13
14 scanf("%s %s", str1, str2);
15
16 //To do
17
18 printf("%s\n", str3);
19
20 return 0;
21 }
22
23 void Add(char *str1,char *str2, char *str3)
24 {
25 int i, j, i1, i2, len1, len2, cnt, tmp;
26 char ch;
27
28 len1 = strlen(str1);
29 len2 = strlen(str2);
30
31 i1 = len1-1;
32 i2 = len2-1;
33
34 j = cnt = 0; //cnt是进位
35
36
37
38 for ( ; i1>=0 && i2>=0; i1--, i2--, j++)
39 {
40 tmp = str1[i1]-'0'+str2[i2]-'0' + cnt;
41 str3[j] = tmp % 10 + '0';
42 cnt = tmp / 10;
43 }
44 while (i1 >= 0)
45 {
46 tmp = str1[i1--] - '0' + cnt;
47 cnt = tmp / 10;
48 str1[j++] = tmp % 10 + '0';
49 }
50 while (i2 >= 0)
51 {
52 tmp = str2[i2--] - '0' + cnt;
53 cnt = tmp / 10;
54 str2[j++] = tmp % 10 + '0';
55 }
56 if (cnt)
57 {
58 str3[j++] = cnt + '0';
59 }
60 str3[j] = '\0';
61
62 for (i=0, j--; j>i; i++, j--)
63 {
64 ch = str3[j];
65 str3[j] = str3[i];
66 str3[i] = ch;
67 }
68 }
69
70 void Minus(char *str1, char *str2, char *str3)
71 {
72 //need str1 > str2
73 int i, j, len, i1, i2, cnt, tmp;
74 char ch;
75
76 i1 = strlen(str1) - 1;
77 i2 = strlen(str2) - 1;
78
79 j = cnt = 0;
80
81 while (i2 >= 0)
82 {
83 tmp = str1[i1]-str2[i2]-cnt;
84 if (tmp < 0)
85 {
86 str3[j] = tmp + 10 + '0';
87 cnt = 1;
88 }
89 else
90 {
91 str3[j] = tmp + '0';
92 cnt = 0;
93 }
94 i2--;
95 i1--;
96 j++;
97 }
98 while (i1 >= 0)
99 {
100 tmp = str1[i1] - '0' - cnt;
101 if (tmp < 0)
102 {
103 str3[j] = tmp + 10 + '0';
104 cnt = 1;
105 }
106 else
107 {
108 str3[j] = tmp + '0';
109 cnt = 0;
110 }
111 i1--;
112 j++;
113 }
114 j--;
115 //去0
116 while (str3[j] == '0' && j>0)
117 {
118 j--;
119 }
120 str3[++j] = '\0';
121
122
123 for (i=0, j--; i < j; i++, j--)
124 {
125 ch = str3[i];
126 str3[i] = str3[j];
127 str3[j] = ch;
128 }
129 }



你可能感兴趣的:(运算)