Java 程序将十进制转换为八进制


在本文中,我们将了解如何将十进制转换为八进制。十进制数是由小数点分隔整数和小数部分的数。八进制数的基数为八,使用 0 到 7 之间的数字。

下面是对同一内容的演示 −

输入

假设我们的输入为 −

Enter the decimal number : 8

输出

所需的输出为 −

The octal value is
10

算法

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

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

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

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

示例 2

此处,该整数已经事先定义,并且获取其值并显示在控制台中。

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

输出

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

更新于:2022 年 2 月 21 日

526 次浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告