zoukankan      html  css  js  c++  java
  • 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
    ", argv[0]);
    11                 return -1;
    12         }
    13         else
    14         {
    15                 t = atoi(argv[1]);
    16                 printf("%d! is %d.
    ", 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
  • 相关阅读:
    iis添加证书
    重谈主键和索引
    关于心跳包的方案探究
    flutter android keystore
    flutter photo_view的改造
    dart 命名规范
    dart 公共变量
    flutter 交互提示方式
    flutter container image FittedBox AspectRatio
    聊聊flutter的UI布局
  • 原文地址:https://www.cnblogs.com/lxw0109/p/atoi.html
Copyright © 2011-2022 走看看