Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

หาค่า Octal Equivalent ของเลขฐานสิบใน C#

วิธีหาค่า Octal (ฐาน 8) จาก Decimal (ฐาน 10) ใน C#:

  1. ใช้ While Loop หารด้วย 8 เก็บเศษในอาร์เรย์
  2. หารตัวเลขด้วย 8 ทีละรอบจนกว่าจะเหลือ 0
while (dec != 0)
{
    oct[i] = dec % 8;
    dec = dec / 8;
    i++;
}

ตัวอย่าง: Decimal 12 -> Octal

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] oct = new int[50];
            int dec = 12;
            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();
        }
    }
}

ผลลัพธ์: 14 (Octal)