![](/img/trans.png)
[英]Why am I getting a NoClassDefFoundError exception rather than a StackOverflow error?
[英]Why do I keep getting back 1011 rather than 1101?
所以,问题是。
当以number = 13和base = 2调用时,下面的递归代码将输出什么?
public static void convert(int number, int base) {
int remainder = number % base;
int quotient = number / base;
if (quotient > 0) convert(quotient, base);
System.out.print(remainder);
我已经在纸上进行了大约一个小时的处理,无论我继续提出1011还是1101。
我是在数学上做错了还是什么?
通过在递归调用之后进行打印,您将以相反的顺序打印出余数,例如2 ^ 0位,2 ^ 1位,依此类推。 而不是2 ^ 3位,2 ^ 2位等。将打印移动到if语句之前,它应该可以正常工作。
我假设代码看起来像
public static void convert(int number, int base) {
int remainder = number % base;
int quotient = number / base;
if (quotient > 0) convert(quotient, base);
System.out.print(remainder);
}
public static void main(String[] args) {
convert(13, 2);
}
迭代:
A) number = 13, base = 2, remainder = 1, quotient = 6;
B) number = 6, base = 2, remainder = 0, quotient = 3;
C) number = 3, base = 2, remainder = 1, quotient = 1;
D) number = 1, base = 2, remainder = 1, quotient = 0; print "1"
c) print "1"
b) print "0"
a) print "1"
因此,看起来输出应为1101。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.