从键盘输入两整数m和n,显示[m,n]之间的十进制二进制八进制十六进制对照表,输入25 31效果如下图。要求不许使用系统提供的进制转换函数。验证理解栈的使用,函数一次书写多次调用的妙用。对齐用\t。java
时间: 2023-06-10 10:08:49 浏览: 141
Java程序十进制转二进制,八进制,十六进制
4星 · 用户满意度95%
以下是Java代码实现:
```java
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入两个整数m和n(以空格隔开):");
int m = input.nextInt();
int n = input.nextInt();
System.out.println("十进制\t二进制\t八进制\t十六进制");
for (int i = m; i <= n; i++) {
System.out.println(i + "\t" + toBinary(i) + "\t" + toOctal(i) + "\t" + toHexadecimal(i));
}
}
// 十进制转二进制
public static String toBinary(int num) {
String binary = "";
Stack<Integer> stack = new Stack<Integer>();
while (num != 0) {
stack.push(num % 2);
num /= 2;
}
while (!stack.isEmpty()) {
binary += stack.pop();
}
return binary;
}
// 十进制转八进制
public static String toOctal(int num) {
String octal = "";
Stack<Integer> stack = new Stack<Integer>();
while (num != 0) {
stack.push(num % 8);
num /= 8;
}
while (!stack.isEmpty()) {
octal += stack.pop();
}
return octal;
}
// 十进制转十六进制
public static String toHexadecimal(int num) {
String hexadecimal = "";
Stack<Character> stack = new Stack<Character>();
int remainder;
while (num != 0) {
remainder = num % 16;
if (remainder < 10) {
stack.push((char) (remainder + '0'));
} else {
stack.push((char) (remainder - 10 + 'A'));
}
num /= 16;
}
while (!stack.isEmpty()) {
hexadecimal += stack.pop();
}
return hexadecimal;
}
}
```
运行结果如下:
```
请输入两个整数m和n(以空格隔开):25 31
十进制 二进制 八进制 十六进制
25 11001 31 19
26 11010 32 1A
27 11011 33 1B
28 11100 34 1C
29 11101 35 1D
30 11110 36 1E
31 11111 37 1F
```
阅读全文