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.

60 lines
1.8 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 computer {
// 将任意进制数转换为十进制数
public static int toDecimal(String number, int base) {
int decimal = 0;
int power = 0;
// 从字符串的末尾开始遍历
for (int i = number.length() - 1; i >= 0; i--) {
char digit = number.charAt(i);
int value;
// 处理0-9的数字字符
if (digit >= '0' && digit <= '9') {
value = digit - '0';
}
// 处理A-F或a-f的十六进制字符
else if (digit >= 'A' && digit <= 'F') {
value = digit - 'A' + 10;
} else if (digit >= 'a' && digit <= 'f') {
value = digit - 'a' + 10;
} else {
throw new IllegalArgumentException("Invalid character in number: " + digit);
}
// 根据当前字符的权重(即它在数中的位置)累加其值
decimal += value * Math.pow(base, power);
power++;
}
return decimal;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入原始进制数和目标进制
System.out.print("输入原始数字的基数2-16: ");
int originalBase = scanner.nextInt();
System.out.print("输入原始数字输入要转换的基数2-16: ");
String originalNumber = scanner.next();
System.out.print("输入要转换的基数2-16: ");
int targetBase = scanner.nextInt();
// 转换并输出结果
int decimal = toDecimal(originalNumber, originalBase);
String convertedNumber = fromDecimal(decimal, targetBase);
System.out.println("转换后的号码是: " + convertedNumber);
scanner.close();
}
}