简体   繁体   English

如何使用动态内存分配将十进制转换为八进制?

[英]How can I use dynamic memory allocation for converting decimal to octal?

I have two pieces of code that I wrote. 我写了两段代码。 This one doesn't work because it writes the code backwards. 这个不起作用,因为它向后写代码。

void convertNum1(long a) {
    while (a!=0) {
        long remainder = 0;
        remainder = a % 8;
        a /= 8;

        cout << remainder;
    }
    cout << endl;
}

I wrote this code because the first one doesn't work. 我写了这段代码,因为第一个代码不起作用。 Basically my idea is to fill up an array with the elements and then count it backwards. 基本上我的想法是用元素填充数组然后向后计数。

void convertNum2(long a) {
    long *pointer = NULL;
    int k = 1;
    long c = a;
    while (c != 0) {
        c/= 8;
        k++;
    }
    pointer = new long[k];

    int rem;
    for (int j = 0;j<k;j++) {
        rem = a / 8;
        *(pointer + j) = rem;
    }
    for (int j = k; j > 0;j--) {
        cout << *(pointer + j);
    }

    delete []pointer;
}

I recommend using a stack . 我建议使用stack Push the octal digits onto the stack, then pop them off (they will be in the correct order). 将八进制数字推入堆栈,然后将其弹出(它们将按正确顺序)。

BTW, you can always cheat and use std::oct I/O manipulator 顺便说一下,你总是可以欺骗并使用std::oct I / O操纵器

std::string Dec_To_Oct(unsigned long number)
{
  static const char octal_char_digits[] = "01234567";
  std::stack<char>  octal_number;
  while (number > 0U)
  {
    octal_digit = number % 8;
    const char d = octal_char_digits[octal_digit];
    octal_number.push(d);
    number = number / 8;
  }
  std::string octal_text;
  while (!octal_number.empty())
  {
     const char d = octal_number.top();
     octal_text += d;
     octal_number.pop();
  }
  return octal_text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM