问题:
Write C++ function to evaluate the following formula for a given
x
:
以下代码是在 Visual Studio 上用 C++ 设计的,用于解决上述问题。但是,每当我运行代码时,返回的是 x
的值;或我输入的相同值。
我不明白可能是什么问题,所以我将不胜感激。
#include <iostream>
using namespace std;
unsigned long fact(int n) {
if (n <= 1) {
return 1;
}
else {
return n * fact(n - 1);
}
}
unsigned long f(int x, int n) {
static unsigned long term;
static unsigned long sum = 0;
do {
term = pow(x, (2 * n + 1)) / fact((2 * n) + 1);
n++;
sum += term;
} while (term < 0.000001);
return sum;
}
int main() {
int y = 0;
int x;
cout << "enter x" << endl;
cin >> x;
cout << f(x, y) << endl;
system("pause");
}
最佳答案
我建议您不要在每次迭代时都计算幂和阶乘。每个下一个 term
都可以通过将前一个乘以 x^2/[n(n+1)]
来生成:
double sinh_in_disguise(const double x) {
const double x_sq = x * x;
double term = x;
double sum = 0;
double n = 2;
while (true) {
const double new_sum = sum + term;
if (new_sum == sum)
break;
sum = new_sum;
term *= x_sq / (n * (n + 1));
n += 2;
}
return sum;
}
int main() {
std::cout.precision(16);
double x = 2.019;
std::cout << sinh_in_disguise(x) << std::endl; // prints 3.699001094869803
std::cout << std::sinh(x) << std::endl; // prints 3.699001094869803
}
关于c++ - 求和到几何序列的无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848942/