考虑序列X1 = 1,X2 = 1 + 1/1,X3 = 1 + 1/1 + 1/1 ...。按此顺序Xn + 1 = 1 + 1/Xn(对于n> = 1)。用Java编写一个计算Xn的方法。随着n的增加,该序列的项越来越接近黄金比率1 + sqrt 5/2〜1.61803398875。 X10与黄金比例有多接近?

这是我编写的程序,但是当我在java中运行它时,它不会编译。我不知道该怎么办,应该在明天到期。请帮忙!

public class Golden Ratio

{
public static final double GOLDEN = ( 1 + Math.sqrt(5))/2;
/**
 * precondition: Class(Golden Ratio), n values
 * precondition: sequence values found
 */
public static double sequence (int n)
{
if (n == 0) {
return 1;
{
public static void main(String[] args)
{
for (int n = 0; n < 40; n++)
{
double diff = Math.abs(sequence(n) - GOLDEN);
System.out.print(n+1+")");
System.out.print(n + 1 < 10 ? " seq " + sequence(n): "seq " + sequence (n))
System.out.print("gld " + GOLDEN);
System.out.print("diff = %.32f\t". diff);
System.out.print("\n");
}
System.out.print("\n");
System.out.print("10)" + "sqe " + sequence(9) + "ln gld + GOLDEN"\t diff = %.32 f\t" + diff);
System.out.print("");
}
}
}

最佳答案

您的职能应完成所有计算工作。您的main方法只是调用它并显示结果。这是它的结构。您仍然需要做计算序列的部分。但是,在进行工作之前,请仔细检查定义。如果X3 = 1 + 1/1 + 1/1,则与说X3 = 3相同,这显然是错误的。

public static double calculateSequence(int n) {
    double sum=0.0;
    for (int i=0; i<n; i++) {
       // do your magic
    }
    return sum;
}

public static void main(String[] args) {
    double answer=calculateSequence(10);
    System.out.println("%f is off by %f", answer, GOLDEN_RATIO - answer);
}

10-07 19:41