Java For循环成递归函数
public class For {
public static void main(String[] args){
for(int i=2; i<=1024; i *= 2){
System.out.println("Count is: " + i);
}
}
public class While {
public static void main(String[] args){
int i = 1;
while (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
}
}
public class DoWhile {
public static void main(String[] args){
int i = 1;
if (i < 1024) {
do { i*=2;
System.out.println("Count is: " + i);
} while (i < 1024);
}
}
如何转换 for 循环/while 循环,使其执行相同的操作,但使用递归函数?
public class For {
public static void main(String[] args){
for(int i=2; i<=1024; i *= 2){
System.out.println("Count is: " + i);
}
}
public class While {
public static void main(String[] args){
int i = 1;
while (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
}
}
public class DoWhile {
public static void main(String[] args){
int i = 1;
if (i < 1024) {
do { i*=2;
System.out.println("Count is: " + i);
} while (i < 1024);
}
}
How would one convert the for loop/while loop so it does the same thing, but using a recursive function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
就像这样:
Like so:
获取
main
的循环并将其放入其自己的带有参数int i
的函数中。在该函数中,将循环重写为i >= 1024
), thenreturn
i*2
。使用参数
1
或2
调用函数,具体取决于您要重写的程序(它们并不完全匹配)。Take the loop of
main
and put it in its own function with an argumentint i
. In that function, rewrite the loop toi >= 1024
), thenreturn
i*2
.Call the function with argument
1
or2
, depending on which of your programs you're rewriting (they don't entirely match).循环循环可以如下所示:
Recurrent loop can look like this:
公共类测试1 {
}
public class Test1 {
}