java中的黄金比例

时间:2017-05-15 23:22:45

标签: java compiler-errors

考虑序列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("");
}
}
}

1 个答案:

答案 0 :(得分:0)

你的功能应该完成所有的计算工作。您的主要方法只是调用它并显示结果。这是它的结构。您仍然需要执行计算序列的部分。但是,在完成工作之前,请仔细检查定义。如果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);
}