求助,为什么输入2会栈溢出,请教大佬

P1035 [NOIP2002 普及组] 级数求和

24r46fg @ 2024-07-09 18:41:58

import java.util.Scanner;
public class P1035 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int k = scanner.nextInt();
        LevelAdd u = new LevelAdd();
        u.t(1, k);
    }
}
public class LevelAdd {
    public int f(int n) {
        if (n == 0) {
            return 0;
        }
        return f(n - 1) + 1 / n;
    }
    public void t(int n, int k) {
        if (f(n) > k) {
            System.out.println(n);
        } else {
            t(++n, k);
        }
    }
}

by 24r46fg @ 2024-07-09 18:51:02

找到问题了,

public double f(int n) {
        if (n == 0) {
            return 0;
        }
        return f(n - 1) + (double)1 / n;
    }

将返回类型化为double就行了,帖子不删了,就做个错误示范


|