头图

以下是Java实现十进制到各种进制的转换的代码示例:

import java.util.Scanner;

public class DecimalToOtherBases {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a decimal number: ");
    int decimalNumber = scanner.nextInt();
  
    System.out.println("Binary: " + convertToBase(decimalNumber, 2));
    System.out.println("Octal: " + convertToBase(decimalNumber, 8));
    System.out.println("Hexadecimal: " + convertToBase(decimalNumber, 16));
  
    scanner.close();
}

public static String convertToBase(int decimalNumber, int base) {
    if (decimalNumber == 0) {
        return "0";
    }
  
    StringBuilder result = new StringBuilder();
    while (decimalNumber > 0) {
        int remainder = decimalNumber % base;
        if (remainder < 10) {
            result.insert(0, remainder);
        } else {
            result.insert(0, (char) ('A' + remainder - 10));
        }
        decimalNumber /= base;
    }
  
    return result.toString();
}

}

这段代码可以让用户输入一个十进制数,然后将其转换为二进制、八进制和十六进制表示。实现了基本的转换功能,满足你的要求。


蓝易云
33 声望3 粉丝