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.
ljy/jinzhi.java

64 lines
1.8 KiB

import java.util.Scanner;
public class jinzhi {
// 将R进制数X转换为十进制
private static int toDecimal(String number, int base) {
int decimalValue = 0;
int power = 1; // 当前位的权重
for (int i = number.length() - 1; i >= 0; i--) {
char digit = number.charAt(i);
int digitValue;
if (Character.isDigit(digit)) {
digitValue = digit - '0'; // 数字字符转为整数
} else {
digitValue = Character.toUpperCase(digit) - 'A' + 10; // 字母字符转为整数
}
decimalValue += digitValue * power;
power *= base; // 更新权重
}
return decimalValue;
}
// 将十进制数转换为S进制
private static String fromDecimal(int number, int base) {
StringBuilder result = new StringBuilder();
while (number > 0) {
int remainder = number % base;
if (remainder < 10) {
result.append((char) ('0' + remainder));
} else {
result.append((char) ('A' + remainder - 10));
}
number /= base;
}
return result.reverse().toString(); // 反转结果
}
// 主方法
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入源进制R (2-16): ");
int baseR = scanner.nextInt();
System.out.print("请输入需要转换的数X (R进制): ");
String numberX = scanner.next();
System.out.print("请输入目标进制S (2-16): ");
int baseS = scanner.nextInt();
// 转换过程
int decimalValue = toDecimal(numberX, baseR);
String result = fromDecimal(decimalValue, baseS);
System.out.println("转换结果: " + result);
}
}