Java递归实现十进制转指定进制时输出结果反转问题求助
问题根因
十进制转N进制的取余计算逻辑中,第一次取余得到的是目标进制的最低位,最后一次取余得到的是最高位。你当前的递归逻辑是先打印当前计算的余数,再触发下一层递归,等于先输出最低位、再输出高位,最终结果自然是反转的。
修复方案
核心调整点
- 把打印余数的操作移到递归调用之后,等最深层递归(最高位计算)执行完成后,再从高位到低位依次打印
- 补充1015余数到AF的映射,适配11~16进制的输出规范
- 新增输入值为0的特殊处理,避免递归直接返回空白内容
修复后的完整代码如下:
import java.util.Scanner; public class DecimalConverter { // 定义16进制以内的余数映射表 private static final char[] BASE_CHARS = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; public static void main(String[] args) { int decimalValue = 0; int targetBase = 0; while (decimalValue != -1){ Scanner input = new Scanner(System.in); System.out.print("Decimal value: "); decimalValue = input.nextInt(); if (decimalValue == -1){ System.out.println("Thank you for using the program. bye!"); System.exit(0); } while (targetBase < 2 || targetBase > 16){ System.out.print("Target base: "); targetBase = input.nextInt(); } System.out.print("Value of " + decimalValue + " in base " + targetBase + " is "); // 处理输入为0的特殊场景 if (decimalValue == 0) { System.out.print(0); } else { recursionFunction(decimalValue, targetBase); } System.out.println(); targetBase = 0; } } public static void recursionFunction(int Decimal, int Base){ int result; if (Decimal == 0) { return; } result = Decimal / Base; // 先递归计算高位 recursionFunction(result, Base); // 递归返回后再打印当前位,保证从高位到低位的输出顺序 System.out.print(BASE_CHARS[Decimal % Base]); } }
测试十进制16转二进制场景,输出结果为10000,符合预期。
内容的提问来源于stack exchange,提问作者Murd
相关产品推荐
相关产品推荐

