The C Programming Language 练习题3-5

来源:互联网 发布:js onclick this 编辑:程序博客网 时间:2024/06/05 02:50

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

代码实现

#include <stdio.h>void itob(int n, char s[], int b);void reverse(char s[]);int main(){    int n, b, i;    char c, s[31];    n = 56789;    b = 8;    itob(n, s, b);    i = 0;    while ((c = s[i]) != '\0')        printf("%c", s[i++]);}void itob(int n, char s[], int b){    int i, j, m;    char c;    i = 0;    do    {        j = n % b;        c = j + '0';        s[i++] = c;        n = n / b;    }    while (n > 0);    s[i] = '\0';    reverse(s);}void reverse(char s[]){    int c, i, j;    for (i = 0, j = strlen(s)-1; i < j; i++, j--)        {        c = s[i];        s[i] = s[j];        s[j] = c;        }}
原创粉丝点击