【问题标题】:Reverse the output of printf function in while loop在while循环中反转printf函数的输出
【发布时间】:2018-04-07 22:48:33
【问题描述】:

我为所选数字的 b-adic 表示编写了一个代码。

#include <stdio.h>

int b_adisch (int a, int b)
{

    int x, y, mod, mod1;

    x = a / b;
    mod1 = a % b;

    printf("%i\n", mod1);

    do {
    y = x / b;
    mod = x % b;
    x = y;
    printf("%i\n", mod);
    } while(x != 0);
    return a ;
}

int main (void)
{
    int a, b;
    printf("pls input a ");
    scanf("%i", &a);
    printf("pls input b ");
    scanf("%i", &b);
    b_adisch(a, b);

    return 0;
}

输出顺序会颠倒 因为 printf 必须放入 while 循环,并且计算从表示的最后一个数字开始。

例如 a = 10 和 b = 2
输出为 0101
但应该是 1010

如何更改我的代码以实现这一点?

【问题讨论】:

  • 嗯..递归?
  • 一周前开始编程所以我不知道这是什么......

标签: c gcc printf do-while


【解决方案1】:

您可以将输出存储在一个数组中,因为它存储在“arr”中,然后以相反的顺序(从头到尾)打印输出。

#include <stdio.h>
int arr[10000]={0};
void b_adisch (int a, int b)
{
    int x, y, mod, mod1,i=0,j;
    x = a / b;
    mod1 = a % b;
    arr[i++]=mod1;
    do {
    y = x / b;
    mod = x % b;
    x = y;
    arr[i++]=mod;
    } while(x != 0);
    for(j=i-1;j>=0;j--)
    printf("%i\n",arr[j]);
}

int main (void)
{
    int a, b;
    printf("pls input a ");
    scanf("%i", &a);
    printf("pls input b ");
    scanf("%i", &b);
    b_adisch(a, b);

    return 0;
}

【讨论】:

  • 非常感谢
  • 10000 有点多,你不觉得吗?考虑到int 现在在大多数硬件上仍然用 32 位表示。
【解决方案2】:

如何更改我的代码以实现这一点?

2 种方法:

计算从最低到最高有效的数字并保存在足够大小的缓冲区中。这类似于 OP 的方法,但保存每个数字的计算结果以供以后打印。

#include <assert.h>
#include <limits.h>

void b_adisch(int value, int base) {
  // Let us work with simple cases first.
  assert(value >= 0);
  assert(base >= 2 && base <= 10);

  // Adequate sized buffer
  char buffer[sizeof value * CHAR_BIT + 1];
  // Start at end
  char *end = &buffer[sizeof buffer - 1];
  *end = '\0';

  do {
    end--;
    int digit = value%base;  // Find least digit
    value /= base;
    *end = digit + '0';  // save the digit as text
  } while (value);

  printf("<%s>\n", end);  // print it as a string
}

使用递归。更彻底的改变;这首先计算并打印更高有效数字的输出。

void b_adischR_helper(int value, int base) {
  // If the value is at least 2 digits, print the most significant digits first
  if (value >= base) {
    b_adischR_helper(value/base, base);
  }
  putchar(value % base + '0');  // Print 1 digit as text
}

void b_adischR(int value, int base) {
  // Let us work with simple cases first.
  assert(value >= 0);
  assert(base >= 2 && base <= 10);

  printf("<");
  b_adischR_helper(value, base);
  printf(">\n");
}

测试

int main() {
  b_adisch(10, 2);
  b_adischR(10, 2);
  b_adisch(INT_MAX, 10);
  b_adischR(INT_MAX, 10);
  b_adisch(INT_MAX, 2);
  b_adischR(INT_MAX, 2);
}

输出

<1010>
<1010>
<2147483647>
<2147483647>
<1111111111111111111111111111111>
<1111111111111111111111111111111>

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多