在计算机中,由于处理器位宽限制,只能处理有限精度的十进制整数加减法,比如在32位处理器计算机中,参与运算的操作数和结果必须在**之间。如果需要进行更大范围的十进制整数加法,需要使用特殊的方式实现,比如使用字符串保存操作数和结果,采取逐位运算的方式。比如下面问题:
9876543210 + 1234567890 =?
让字符串 num1 = "9876543210",字符串 num2 = "1234567890",结果保存在字符串result中。要求编程实现上述高精度的十进制加法。
01 |
#include<stdio.h> |
02 |
#include<string.h> |
03 |
int NumAdd( const char *first, const char *second, char *result, int resultlen) |
04 |
{ |
05 |
int numlen[2]; |
06 |
numlen[0] strlen (first); |
07 |
numlen[1] strlen (second); |
08 |
int maxlen; |
09 |
maxlen= |
10 |
|
11 |
if (resultlen< |
12 |
return -1; |
13 |
|
14 |
int n; |
15 |
int byteValue[2]; |
16 |
int curByteResult; |
17 |
int addByteResult; |
18 |
|
19 |
curByteResult=addByteResult=0; |
20 |
21 |
//从左到右进行循环 |
22 |
for (n |
23 |
{ |
24 |
--numlen[0]; |
25 |
--numlen[1]; |
26 |
27 |
if (numlen[0] |
28 |
byteValue[0] '0' ; |
29 |
else |
30 |
byteValue[0] |
31 |
|
32 |
if (numlen[1] |
33 |
byteValue[1] '0' ; |
34 |
else |
35 |
byteValue[1] |
36 |
|
37 |
curByteResult |
38 |
if (curByteResult>=10) |
39 |
{ |
40 |
curByteResult |
41 |
addByteResult |
42 |
|
43 |
if (n==0) |
44 |
{ |
45 |
result[0] '1' ; |
46 |
++result; |
47 |
} |
48 |
else |
49 |
{ |
50 |
++result[n-1]; //处理进位 |
51 |
} |
52 |
result[n] '0' +curByteResult; |
53 |
} |
54 |
else |
55 |
{ |
56 |
result[n] '0' +curByteResult |
57 |
addByteResult |
58 |
} |
59 |
} |
60 |
result[n] |
61 |
return 1; |
62 |
} |
63 |
64 |
65 |
int main( |
66 |
{ |
67 |
char szstr1[]= "9876543210" ; |
68 |
char szstr2[]= "1234567890" ; |
69 |
char result[100]; |
70 |
|
71 |
NumAdd(szstr1,szstr2,result,100); |
72 |
printf ( "result ,result); |
73 |
74 |
return 0; |
75 |
} |