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.
|
|
|
|
package Calculator;
|
|
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
|
|
public class Calculator {
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
Scanner scanner = new Scanner(System.in);
|
|
|
|
|
<<<<<<< HEAD
|
|
|
|
|
=======
|
|
|
|
|
System.out.print("请输入源进制(2-16):");
|
|
|
|
|
int fromBase = scanner.nextInt();
|
|
|
|
|
System.out.print("请输入目标进制(2-16):");
|
|
|
|
|
int toBase = scanner.nextInt();
|
|
|
|
|
>>>>>>> origin/master
|
|
|
|
|
System.out.print("请输入要转换的数:");
|
|
|
|
|
String num = scanner.nextLine();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 调用转换方法
|
|
|
|
|
String converted = convertBase(num, fromBase, toBase);
|
|
|
|
|
|
|
|
|
|
System.out.printf("%s (%d进制) 转换为 (%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();
|
|
|
|
|
}
|
|
|
|
|
}
|