- 好久没有写 C++ 题目了,稍稍回归一下,做题确实简单。
- 如果想感受一下真正的 C++ 变成,可以查看我正在推进的开源项目:mmCEsim
利用技术展开计算
f
(
x
)
=
g
(
2
)
x
3
−
g
(
3
)
x
5
+
g
(
4
)
x
7
+
⋯
+
(
−
1
)
n
g
(
n
)
x
2
n
−
1
,
f(x)=g(2)x^3-g(3)x^5+g(4)x^7+\cdots+(-1)^ng(n)x^{2n-1},
f(x)=g(2)x3−g(3)x5+g(4)x7+⋯+(−1)ng(n)x2n−1,
where
g
(
m
)
=
(
m
−
2
)
/
(
m
−
1
)
g(m)=(m-2)/(m-1)
g(m)=(m−2)/(m−1).
其余格式要求略。
/**
* @file main.cpp
* @brief Calculate the sum of a series.
*
* @author Teddy van Jerry
* @date 2022-10-27
*/
#include
#include
#include
/**
* @brief Calculate the g function
*
* @param m the integer (at least 2)
* @return (double) the result of g function
*/
inline double g(int m) {
assert(m > 1 && "'m' should be at least 2!");
return static_cast<double>(m - 2) / (m - 1);
}
/**
* @brief Calculate the f function
*
* @param x the number of parameters
* @param n the number of series
* @return (double) the result of f function
*/
double f(double x, int n = 10) {
assert(n > 1 && "'n' should be at least 2!");
double s = 0;
for (int i = 2; i != n; ++i) {
s += (1 - i % 2 * 2) * g(i) * std::pow(x, 2 * i - 1);
}
return s;
}
int main(int argc, const char* argv[]) {
double x;
int n;
std::cout << "Please input x: ";
std::cin >> x;
std::cout << "Please input n (n > 1): ";
std::cin >> n;
if (n < 2) {
std::cerr << "n should be at least 2!\n";
return 1;
} else {
std::cout << "f(" << x << ") = " << f(x, n)
<< ", (n = " << n << ")" << std::endl;
}
return 0;
}
Please input x: 0.3
Please input n (n > 1): 10
f(0.3) = -0.00108267, (n = 10)
Please input x: 0.3
Please input n (n > 1): -10
n should be at least 2!
assert
进行参数检查;std::pow
函数可以简便实现乘方。ALL RIGHTS RESERVED © 2022 Teddy van Jerry
欢迎转载,转载请注明出处。
Teddy van Jerry 的 个人主页
Teddy van Jerry 的 CSDN 导航页
Teddy van Jerry 的 GitHub 主页
Teddy van Jerry 的 博客主页