atoi函数的使用实例:【Ubuntu环境】
main.c:
1 #include2 #include 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 else14 {15 t = atoi(argv[1]);16 printf("%d! is %d.\n", t, factorial(t));17 }18 return 0;19 }
factorial.c:
1 #include2 3 int factorial(int f)4 {5 if(f <= 1)6 return 1;7 else8 return factorial(f - 1) * f;9 }
编译运行:
Compile:
lxw@lxw-Aspire-4736Z:~/lxw0109/C++$ gcc -o factorial main.c factorial.cExecute:lxw@lxw-Aspire-4736Z:~/lxw0109/C++$ ./factorial 44! is 24.lxw@lxw-Aspire-4736Z:~/lxw0109/C++$ ./factorial 55! 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 }