分享

C语言--将整数n转换为以b进制的数。保存到s中

 心不留意外尘 2016-05-19

http://9195095.blog.51cto.com/9185095/1705669

2015

问题:

    编写一个函数itob(int n,char s[], int b),将整数n转换为以b进制的数。保存到s中。j_0071.gif

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
void reverse(char *left, char *right)
{
    while (left < right)
    {
        char tmp = *left;
        *left = *right;
        *right = tmp;
        left++;
        right--;
    }
}
void itob(int n, char s[], int b)
{
        char *start;
        char *end;
        start = s;
        while (n)
        {
            if (b <= 10)
                *s = (n % b) + '0';
            else if (b == 16)
                *s = "0123456789abcdef"[n % b];
            s++;
            n /= b;
        }
        *s = '\0';
        end = s - 1;
        reverse(start, end);
}
int main()
{
     
    char arr[20];
    int b = 0;
    int num = 0;
    printf("请输入要转换的数 和几进制数\n");
    scanf_s("%d,%d", &num, &b);
    itob(num, arr, b);
    printf("%s\n", arr);
    return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多