zoukankan      html  css  js  c++  java
  • 《C程序设计语言》 练习3-5

    问题描述

      练习 3-5 编写函数 itob(n, s, b),将整数n转换为以b为底的数,并将转换结果以字符的形式保存到字符串s中。例如,itob(n, s, 16)把整数n格式化成十六进制整数保存在s中。

      Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s . In particular, itob(n,s,16) formats n as a hexadecimal integer in s .

    代码如下

    #include<stdio.h>
    #include<string.h>
    
    void reverse(char s[])//字符串倒置函数
    {
        int i,j,t;
        for ( i = 0,j=strlen(s)-1; i <j; i++,j--)
        {
            t = s[i];
            s[i] = s[j];
            s[j] = t;
        }
    }
    void itob(int n,char s[],int b)
    {
        int sign,i;
        static char b_numbers[]={"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
        if ((sign=n)<0)
        {
            n = -n;
        }
        i=0;
        do
        {
            s[i++] = b_numbers[n % b];
        } while ((n/=b)>0);
        if (sign<0)
        {
            s[i++]='-';
        }
        s[i]='';
        reverse(s);
    }
    int main()
    {
        char array[100];
        int n,b;
        printf("请输入要转换的十进制数:");
        scanf("%d",&n);
        putchar('
    ');
        printf("转换为多少进制:");
        scanf("%d",&b);
        putchar('
    ');
        itob(n,array,b);
        printf("结果为:");
        for (int i = 0; array[i]!=''; i++)
        {
            printf("%c",array[i]);
        }
        putchar('
    ');
        return 0;
    }
    

      

    运行结果

  • 相关阅读:
    取三级分销上下级用户id
    Map集合
    Log4j
    异常
    逻辑运算符
    变量
    变量名命名规则
    命名法
    Nessus
    Nmap扫描工具
  • 原文地址:https://www.cnblogs.com/jerryleesir/p/12933511.html
Copyright © 2011-2022 走看看