atoi函数的一种实现

atoi函数的使用实例:【Ubuntu环境】

main.c:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 extern int factorial(int f);    //external function:如果写extern是显式的外部声明;不写也对,只是隐式的而已
 4 
 5 int main(int argc, char ** argv)
 6 {
 7         int t;
 8         if(argc < 2)
 9         {
10                 printf("The format of the input: %s number\n", argv[0]);
11                 return -1;
12         }
13         else
14         {
15                 t = atoi(argv[1]);
16                 printf("%d! is %d.\n", t, factorial(t));
17         }
18         return 0;
19 }
View Code

 

factorial.c:

1 #include <stdio.h>
2 
3 int factorial(int f)
4 {
5         if(f <= 1)
6                 return 1;
7         else
8                 return factorial(f - 1) * f;
9 }
View Code

 

编译运行:

Compile:
lxw@lxw-Aspire-4736Z:~/lxw0109/C++$ gcc -o factorial main.c factorial.c
Execute:
lxw@lxw-Aspire-4736Z:~/lxw0109/C++$ ./factorial 4
4! is 24.
lxw@lxw-Aspire-4736Z:~/lxw0109/C++$ ./factorial 5
5! is 120.

 

附:atoi函数的一种实现:

 1 int myAtoi(const char* str) 
 2 { 
 3     int sign = 0,num = 0; 
 4     assert(NULL != str); 
 5     while (*str == ' ') 
 6     { 
 7         str++; 
 8     } 
 9     if ('-' == *str) 
10     { 
11         sign = 1; 
12         str++; 
13     } 
14     while ((*str >= '0') && (*str <= '9')) 
15     { 
16         num = num * 10 + (*str - '0'); //就是这一行,将对应字符转化为数字
17         str++; 
18     } 
19     if(sign == 1) 
20         return -num; 
21     else 
22         return num; 
23 }
View Code

 

posted @ 2013-10-27 13:25  XiaoweiLiu  阅读(317)  评论(0编辑  收藏  举报