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

โปรแกรม Java แปลงเลขฐานสิบเป็นฐานแปด (Decimal to Octal)

ในบทความนี้ เราจะเรียนรู้วิธีแปลงเลขฐานสิบ (Decimal) เป็นเลขฐานแปด (Octal) ในภาษา Java เลขฐานสิบใช้ตัวเลข 0-9 ส่วนฐานแปดใช้ 0-7

ตัวอย่างการทำงาน

อินพุต:

Enter the decimal number: 8

เอาต์พุต:

The octal value is 10

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. ประกาศตัวแปร: my_input, i, j, อาร์เรย์ my_octal
  3. รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
  4. ใช้ลูป while (input != 0): คำนวณ my_input % 8 เก็บในอาร์เรย์, หาร my_input ด้วย 8, เพิ่ม index
  5. วนลูป for พิมพ์อาร์เรย์ย้อนกลับ (จาก index สุดท้ายถึง 0)
  6. จบโปรแกรม

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;

public class DecimalToOctal {
    public static void main(String[] args) {
        int my_input, i, j;

        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the decimal number: ");
        my_input = my_scanner.nextInt();

        int[] my_octal = new int[100];
        System.out.println("The octal value is:");

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

        for (j = i - 1; j >= 0; j--) {
            System.out.print(my_octal[j]);
        }
    }
}

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class DecimalToOctal {
    public static void main(String[] args) {
        int my_input = 8, i, j;

        System.out.println("The decimal number is defined as " + my_input);

        int[] my_octal = new int[100];
        System.out.println("The octal value is:");

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

        for (j = i - 1; j >= 0; j--) {
            System.out.print(my_octal[j]);
        }
    }
}

วิธีทางเลือก: ใช้เมธอด built-in

int decimal = 8;
String octal = Integer.toOctalString(decimal);
System.out.println("Octal: " + octal); // Output: 10

เมธอด Integer.toOctalString() ใช้งานง่ายกว่าและมีประสิทธิภาพดีกว่า แนะนำให้ใช้ในโค้ดจริง