【问题标题】: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 中 n 的数字
【发布时间】:2017-05-04 19:55:28
【问题描述】:

我需要用 C 语言编写一个程序,该程序将采用自然数 n 和底数 b(假设 b 在区间 [2,10] 内),并将从左开始输出以 b 为底数的数字 n 的数字对。例如,如果 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。我该如何解决这个问题?

【问题讨论】:

  • 只有当n 不能被基数整除时,您的方法才有效。此外,它会破坏以小基数表示的大(ish)数字,因为这样您就可以轻松地溢出number 的容量。我建议以相反的顺序计算数字——从最低到最高——并将它们存储在一个数组中,同时保持对有多少的计数。我相信你可以自己解决如何输出结果。
  • 我看到了这个,我看到了这个……啊,这里是:stackoverflow.com/questions/21133701/… 它是递归完成的,但你也可以线性完成。

标签: c numbers base


【解决方案1】:

最好使用缓冲区来编写解决方案:

void print_base(int n, int b)
{
  static char const digits[] = "0123456789ABCDEF";
  char buffer[16] = { '\0' };
  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);
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2020-07-20
    • 1970-01-01
    相关资源
    最近更新 更多