簡體   English   中英

如何使用動態內存分配將十進制轉換為八進制?

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

我寫了兩段代碼。 這個不起作用,因為它向后寫代碼。

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

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

我寫了這段代碼,因為第一個代碼不起作用。 基本上我的想法是用元素填充數組然后向后計數。

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;
}

我建議使用stack 將八進制數字推入堆棧,然后將其彈出(它們將按正確順序)。

順便說一下,你總是可以欺騙並使用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