You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
firstwork/jinzhi.java

71 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import java.util.Scanner;
public class jinzhi {
// 将数字从 'fromBase' 转换为 'toBase'
public static String convertBase(String number, int fromBase, int toBase) {
// 第一步:从 'fromBase' 转换为十进制base 10
int decimalNumber = 0;
int length = number.length();
// 将输入数字转换为十进制
for (int i = 0; i < length; i++) {
char digit = number.charAt(length - 1 - i);
int value;
if (Character.isDigit(digit)) {
value = digit - '0'; // 将字符转换为 0-9 的整数
} else {
value = Character.toUpperCase(digit) - 'A' + 10; // 将字符转换为 A-F 的整数
}
decimalNumber += value * Math.pow(fromBase, i);
}
// 第二步:从十进制转换为目标进制
if (decimalNumber == 0) {
return "0"; // 如果数字为零,返回 "0"
}
StringBuilder result = new StringBuilder();
// 将十进制数字转换为目标基数
while (decimalNumber > 0) {
int remainder = decimalNumber % toBase;
if (remainder < 10) {
result.append((char) (remainder + '0')); // 添加 0-9 的数字
} else {
result.append((char) (remainder - 10 + 'A')); // 添加 A-F 的字母
}
decimalNumber /= toBase;
}
// 反转结果,因为我们是从后向前构建的
return result.reverse().toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入数字和基数
System.out.print("请输入数字: ");
String number = scanner.nextLine();
System.out.print("请输入原始进制 (2 到 16): ");
int fromBase = scanner.nextInt();
System.out.print("请输入目标进制 (2 到 16): ");
int toBase = scanner.nextInt();
// 验证基数
if (fromBase < 2 || fromBase > 16 || toBase < 2 || toBase > 16) {
System.out.println("基数必须在 2 到 16 之间。");
return;
}
// 转换数字并打印结果
String result = convertBase(number, fromBase, toBase);
System.out.println("进制为 " + fromBase + " 的数: " + number + " 在进制为 " + toBase + " 的数是: " + result );
scanner.close();
}
}