system_of_numeration/demo.java

49 lines
1.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 demo {
// 将R进制数转换为10进制
public static int toDecimal(String number, int base) {
return Integer.parseInt(number, base);
}
// 将10进制数转换为R进制数
public static String fromDecimal(int number, int base) {
StringBuilder sb = new StringBuilder();
while (number > 0) {
int remainder = number % base;
// 对于大于9的数字用字母表示
if (remainder >= 10) {
sb.append((char) ('A' + remainder - 10));
} else {
sb.append(remainder);
}
number /= base;
}
return sb.reverse().toString(); // 反转字符串以得到正确的顺序
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入源进制和目标进制
System.out.print("请输入进制: ");
int sourceBase = scanner.nextInt();
System.out.print("请输入目标进制: ");
int targetBase = scanner.nextInt();
// 输入源进制数
System.out.print("请输入进制数字: ");
String sourceNumber = scanner.next();
// 转换过程
int decimalValue = toDecimal(sourceNumber, sourceBase);
String targetNumber = fromDecimal(decimalValue, targetBase);
// 输出结果
System.out.printf("转换结果: %s(%d) -> %s(%d)\n", sourceNumber, sourceBase, targetNumber, targetBase);
scanner.close();
}
}