zoukankan      html  css  js  c++  java
  • B00006 函数itoa()

    这是一个通用的基础程序,将整型数转换为数字字符串

    其中需要用到字符串逆序转换函数reverse()。

    该程序来自K&C的《C程序设计语言》一书。

    程序如下:

    /* itoa 带符号的整数转换字符串 */
    
    #include <stdio.h>
    
    #include <string.h>
    void reverse(char s[])
    {
        int i,j;
        int c;
    
        for(i=0,j=strlen(s)-1; i<j;i++,j--)
        {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
        }
    }
    
    void itoa(int n,char s[])
    {
        int sign;
    
        if((sign=n) < 0)
            n = -n;
    
        int i=0; //index of s
        do
        {
            s[i] = n%10 + '0';
            i++;
        }
        while((n /= 10)>0);
    
        if(sign <0)
        {
            s[i++] = '-';
        }
    
        s[i] = '';
        reverse(s);
    }
    
    int main(void)
    {
        char s[1024];
    
        itoa(-567, s);
        printf("%d %s
    ", -567, s);
    
        itoa(1234567, s);
        printf("%d %s
    ", 1234567, s);
    
        itoa(-1234567, s);
        printf("%d %s
    ", -1234567, s);
    
        return 0;
    }
    关键代码:

    #include <string.h>
    void reverse(char s[])
    {
        int i,j;
        int c;
    
        for(i=0,j=strlen(s)-1; i<j;i++,j--)
        {
            c = s[i];
            s[i] = s[j];
            s[j] = c;
        }
    
        //int m = N;
    }
    
    void itoa(int n,char s[])
    {
        int sign;
    
        if((sign=n) < 0)
            n = -n;
    
        int i=0; //index of s
        do
        {
            s[i] = n%10 + '0';
            i++;
        }
        while((n /= 10)>0);
    
        if(sign <0)
        {
            s[i++] = '-';
        }
    
        s[i] = '';
        reverse(s);
    }
    运行结果:

    -567 -567
    1234567 1234567
    -1234567 -1234567

  • 相关阅读:
    phpcms 的getcache()函数
    git 上配置公钥
    linux 上git安装
    mac上php的扩展yaf安装
    Linux常用指令---grep(搜索过滤)
    mac virtualbox+vagrant安装
    nginx配置location及rewrite规则重写
    mac php环境搭建
    nginx.pid丢失问题
    git操作教程详解
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564864.html
Copyright © 2011-2022 走看看