1: $ cat printd.C
2: #include <stdio.h>
3: // First version
4: void printd(long d) {
5:
6: if (d < 0) {
7: putchar ('-');
8: d = -d;
9: }
10: if (d / 10)
11: printd (d / 10);
12: //putchar (d % 10 + '0');
13: putchar ("0123456789"[d % 10]);
14: }
15:
16: /* Second Version
17: void printneg (int d);
18:
19: void printd (int d) {
20: if (d <0) {
21: putchar ('-');
22: printneg (d);
23: }
24: else
25: printneg (-d);
26: }
27:
28: void printneg (int d) {
29: if (d <= -10)
30: printneg (d/10);
31: putchar ("0123456789"[-(d % 10)]);
32: }
33: */
34:
35: int main () {
36: int a = 20;
37: int b = 303;
38: int c = -10;
39: int d = -2147483648; //max value for 4bytes int
40:
41: printd(a);
42: puts("");
43: printd(b);
44: puts("");
45: printd(c);
46: puts("");
47: printd(d);
48: puts("");
49: printf("\nc in original format: %d!\n", c);
50: printf("The decimal format of '0' is: %d!\n", '0');
51: printf("The decimal format of 'a' is: %d!\n", 'a');
52: printf("The decimal format of 'A' is: %d!\n", 'A');
53:
54: }
1. 之所以用0123456789不用d % 10 + ‘0’是因为避免某些特殊的character set造成错误
2. 因为一个变量当作为有符号数时可以表示的负数比正数的绝对值更大一些,比如8bit,可以表示-128~127。所以第一个版本当碰到最小值的时候,转成正数会overflow。第二个版本直接用负数作为输出,可以输出负的最大值。
Version1:
Version2: