C评估递归序列 - 预期表达式错误

时间:2015-09-30 03:38:54

标签: c

我试图为最多n = 60的值编写这个递归序列。我知道x0 = 1。

Xn + 1 = 2 ^(n + 1)*(sqrt(1 + 2 ^ -n * Xn) - 1)

到目前为止我已经

int main ()
{
    // first term x0 = 1
    double xn = 1;
    double x;
    double squareRoot = 1 + (pow(2, -x) * xn);

    for (x = 1; x <= 60; x++)
    {
        double xn = pow(2, x) * double sqrt(squareRoot) - 1);
        printf("%f\n", xn);
    }

}

但我在有双倍sqrt的行上得到预期的表达式错误。

3 个答案:

答案 0 :(得分:2)

1。此处有一个额外的括号。

double xn = pow(2, x) * double sqrt(squareRoot) - 1);

你不需要在这里提及类型 - double sqrt(squareRoot)。你可以这样写 -

double xn = pow(2, x) * (sqrt(squareRoot) - 1);

2。此声明也会产生问题 -

double x;
double squareRoot = 1 + (pow(2, -x) * xn);    //this statement

for (x = 1; x <= 60; x++)

您在x中使用pow,但它在外部循环,x在循环之前未初始化。因此,您需要在此声明之前初始化x

答案 1 :(得分:1)

正如其他答案所述,您的代码在此行中存在语法错误:

double xn = pow(2, x) * double sqrt(squareRoot) - 1);

此处括号不均衡,因为您还有)而不是(。另外,您不能像{I} double一样放置sqrt({1}}返回double

下面我放置了一些代码,其中包含了我如何解释方程式的注释,以及关于它如何写成模糊的注释:

#include <math.h>
#include <stdio.h>

int main() {
    int n;

    // You mentioned that x0 is 1.0 and so the variable which is updated is initialized as 1.0
    double x = 1.0;

    // Goal: Xn+1 = 2^(n+1) * (sqrt( 1 + 2^-n*Xn) - 1)
    // Notes:
    // - I named Xn as x to separate the updated variable from the iteration variable
    // - I interpreted "2^-n*Xn" as "pow(2.0, -n) * x" (rather than "pow(2.0, -n * x)")
    for (n = 1; n < 60; n++) {
        // Term A: 2^(n+1)
        double termA = pow(2.0, n + 1.0);

        // Term B: (sqrt( 1 + 2^-n*Xn) - 1)
        // Note that this involves the updated variable, it must be in the loop
        double termB = sqrt(1.0 + pow(2.0, -n) * x) - 1.0;

        // Update x: termA * termB
        x = termA * termB;
        printf("%f\n", x);
    }

    return 0;
}

为了清晰起见而添加

int main() {
    int n;

    double x = 1.0;
    for (n = 1; n < 60; n++) {
        // These are temporary values assigned every iteration
        // Note however that unlike your code "pow(2.0, -n) * x" is evaluated
        // every iteration and so it updates to reflect your desired equation
        // In your code you used "squareRoot" which did not update every iteration
        double termA = pow(2.0, n + 1.0);
        double termB = sqrt(1.0 + pow(2.0, -n) * x) - 1.0;

        // This updates the value of "x" every iteration
        // "x" corresponds to what you called "Xn" in your equation
        x = termA * termB;
        printf("%f\n", x);
    }

    return 0;
}

答案 2 :(得分:0)

double xn = pow(2, x) * double sqrt(squareRoot) - 1);
//                      ^^^^^^                     ^
//                      delete                 unbalanced

还有其他逻辑错误,但我会留下它们供您查找和解决。