Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để chuyển đổi thập phân sang bát phân

Trong bài viết này, chúng ta sẽ hiểu làm thế nào để chuyển đổi thập phân sang bát phân. Số thập phân là số có phần nguyên và phần thập phân được phân tách bằng dấu thập phân. Số bát phân có cơ số là tám và sử dụng số từ 0 đến 7.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Enter the decimal number : 8

Đầu ra

Đầu ra mong muốn sẽ là -

The octal value is
10

Thuật toán

Step 1 - START
Step 2 - Declare three integer value namely my_input, I and j and an integer array my_octal
Step 3 - Read the required values from the user/ define the values
Step 4 – Using a while condition of input not equal to 0, compute my_input % 8 and store it
to my_octal[i]
Step 5 - Compute my_input / 8 and assign it to ‘my_input’, increment ‘i’ value.
Step 6 – Iterating using a for loop, print the ‘my_octal’ array
Step 7- Stop

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để chuyển đổi thập phân sang bát phân .

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

Đầu ra

Required packages have been imported
A reader object has been defined
Enter the decimal number : 8
The octal value is
10

Ví dụ 2

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

public class DecimalToOctal {
   public static void main(String[] args){
      int my_input, i, j;
      my_input = 8;
      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]);
   }
}

Đầu ra

The decimal number is defined as 8
The octal value is
10