[英]C evaluating a recursive sequence - expected expression error
我正在嘗試為高達 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的那一行上得到了預期的表達式錯誤。
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++)
在這里,您在pow
使用x
但它在循環外,並且x
直到循環才被初始化。 所以你需要在這個語句之前初始化x
。
正如其他答案中提到的,您的代碼在這一行中有語法錯誤:
double xn = pow(2, x) * double sqrt(squareRoot) - 1);
這里的括號不平衡,因為你有一個)
比(
。此外,你不能像你那樣放置double
(也不需要它,因為sqrt
返回一個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;
}
double xn = pow(2, x) * double sqrt(squareRoot) - 1);
// ^^^^^^ ^
// delete unbalanced
還有其他邏輯錯誤,但我會把它們留給你去發現和解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.