From 0c506dcbc60ff8ad4bcfd63b84bc2fc419880771 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=9F=8E?= <2304508674@qq.com> Date: Thu, 10 Oct 2024 16:39:55 +0800 Subject: [PATCH] 1 --- Calculator.java | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Calculator.java diff --git a/Calculator.java b/Calculator.java new file mode 100644 index 0000000..5405f22 --- /dev/null +++ b/Calculator.java @@ -0,0 +1,44 @@ +import java.util.Scanner; + +public class Calculator { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("请输入要转换的数:"); + String num = scanner.nextLine(); + + System.out.print("请输入源进制(2-16):"); + int fromBase = scanner.nextInt(); + + System.out.print("请输入目标进制(2-16):"); + int toBase = scanner.nextInt(); + + // 调用转换方法 + String converted = convertBase(num, fromBase, toBase); + + System.out.printf("%s (base %d) 转换为 base %d 是 %s%n", num, fromBase, toBase, converted); + } + + public static String convertBase(String num, int fromBase, int toBase) { + // 将给定的fromBase进制数转换为十进制数 + int decimalNum = Integer.parseInt(num, fromBase); + + // 定义字符集以表示大于10的进制数 + char[] digits = "0123456789ABCDEF".toCharArray(); + + // 如果目标进制是10,则直接返回decimalNum + if (toBase == 10) { + return String.valueOf(decimalNum); + } + + // 否则,从十进制转换为目标进制 + StringBuilder result = new StringBuilder(); + while (decimalNum > 0) { + int remainder = decimalNum % toBase; + result.insert(0, digits[remainder]); + decimalNum /= toBase; + } + + return result.toString(); + } +}