用 C 编写一个程序,它接受一个自然数 n 和基数 b 并输出 b 中 n 的数字

Write a program in C that takes a natural number n and base b and outputs digits of n in b

我需要用C语言编写一个程序,它将取自然数n和基数b(假设b在区间[2,10]内)并输出数字n的基数b的数字,从左到右。例如,如果 n=38 和 b=3,输出应该是 1102。这是我试过的:

#include<stdio.h>

int main(void) {

    int n,b,number=0,digit=0;
    scanf("%d", &n);
    scanf("%d", &b);

    while(n>0) {
    digit=n%b;
    number=number*10+digit;
    n=n/b;
    }

    while(number>0) {
    printf("%d", number%10);
    number=number/10;
    }

    return 0;
}

这适用于 n=38 和 b=3,但是如果我以 n=8 和 b=2 为例,输出为 1,而它应该是 1000。我该如何解决这个问题?

使用缓冲区来编写解决方案是一个更好的主意:

void print_base(int n, int b)
{
  static char const digits[] = "0123456789ABCDEF";
  char buffer[16] = { '[=10=]' };
  char * buff = buffer + 15;

  if ((b >= sizeof digits) || (b <= 1))
    return; // error
  for (; n > 0; n /= b)
    *--buff = digits[n % b]; // move the char pointer backward then write the next digit
  printf("%s\n", buff);
}

您必须在缓冲区中向后写入(或向前写入,然后反转字符串),因为使用您的方法,您首先获得最小的数字。