200鱼币悬赏!!!如何将问题中的循环转换成递归??
本帖最后由 清芷在沅湘 于 2022-4-6 22:37 编辑import java.util.Scanner;
public class Puzzle{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("请输入n的值:");
int n = input.nextInt();
int i;
double last = n;
for (i = n;i > 0;i--){
last = i-1 + 1.0/last;
}
System.out.println("答案是" + last);
}
}如何将图中的循环转换成递归??
/*
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入n的值:");
int n = input.nextInt();
int i;
double last = n;
for (i = n; i > 0; i--) {
last = i - 1 + 1.0 / last;
}
System.out.println("答案是" + last);
}
}
*/
import java.util.Scanner;
public class Puzzle2{
public static double calc(int n, double last) {
if(n <= 0) return last;
return calc(n - 1, n - 1 + 1.0 / last);
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("请输入n的值: ");
int n = input.nextInt();
System.out.println("答案是: " + calc(n, n));
input.close();
}
}
抢沙发 是指for循环吗{:10_248:} andy大宝 发表于 2022-4-6 22:22
是指for循环吗
这不已经是for循环了吗 {:10_266:} {:10_277:} tianlai7266 发表于 2022-4-6 23:05
蹭币,打灭!{:10_283:} 200鱼币结贴吧
public static double myLast(double n ,double l) {
if (n==1){ // 结束条件
return n-1+1.0/l;
}else {
return myLast(n-1, n-1+1.0/l); //递归
}
} 666666666 好高级,学习学习
页:
[1]