如何使用 C# 將十進位制轉換成八進位制?


若要得到八進位制的等價形式,為十進位制值使用一個 while 迴圈,並將餘數儲存在八進位制指定的陣列中。這裡,我們透過 mod 8 將餘數設定在陣列中。

然後將該數字除以 8 −

while (dec != 0) {
   oct[i] = dec % 8;
   dec = dec / 8;
   i++;
}

讓我們來看看完整的程式碼。

這裡,我們的十進位制數字為 18 −

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {

         int []oct = new int[30];

         // decimal
         int dec = 18;

         int i = 0;
         while (dec != 0){
            oct[i] = dec % 8;
            dec = dec / 8;
            i++;
         }

         for (int j = i - 1; j >= 0; j--)
         Console.Write(oct[j]);

         Console.ReadKey();
      }
   }
}

更新於: 2020 年 6 月 21 日

331 次瀏覽

助力你的職業

完成課程並取得認證

開始
廣告
© . All rights reserved.