c - 在c中没有基本库的情况下显示int

标签 c

因为我需要在不使用 C 中的简单库的情况下显示 int。我只能使用这个函数 putch 和 cpus。 我知道这可能看起来有点奇怪,但这是我的任务。 欢迎使用 atoi 和 itoa 函数。 如果您有什么想法,请分享。

最佳答案

这是 itoa 的实现:

/* strlen: return length of string s */
int strlen(char *s)
{
    int i;
    while (*s++) i++;
    return i;
}

/* reverse:  reverse string s in place */
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;
    }
}

/* itoa:  convert n to characters in s */
void itoa(int n, char s[])
{
    int i, sign;

    if ((sign = n) 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        s[i++] = n % 10 + '0';   /* get next digit */
    } while ((n /= 10) > 0);     /* delete it */
    if (sign 0)
    s[i++] = '-';
    s[i] = '\0';
    reverse(s);
} 

你可以这样调用它:

int main(void)
{
    int x = 1024;
    char s[100];

    memset(s, 0, sizeof(s)-1);
    itoa(x, s);

    for (i = 0; i < strlen(s); i++)
        putchar(s[i]);
}

关于c - 在c中没有基本库的情况下显示int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952186/

相关文章:

c - 添加源文件后,gcc 不会让我使用 'just compile' c 源

c - x86-64 System V abi - 参数传递的参数分类

c - 有没有更好的方法来排序浮点操作数?

c - pthread_mutex_lock 仅适用于 sleep

c++ - 在您指定的 wxWidgets 目录中找不到匹配的调试配置。

c - 为什么将指针到指针作为参数传递给函数

c - mdb工具sql查询表 namespace 分隔

c - scanf() 在文件处理中不起作用?

c# - 将文本从字体添加到视频帧

c - 线程和同步