【C++ 程序】级数求和

  • 好久没有写 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)x3g(3)x5+g(4)x7++(1)ng(n)x2n1,
where g ( m ) = ( m − 2 ) / ( m − 1 ) g(m)=(m-2)/(m-1) g(m)=(m2)/(m1).

其余格式要求略。

代码

/**
 * @file main.cpp
 * @brief Calculate the sum of a series.
 *
 * @author Teddy van Jerry
 * @date 2022-10-27
 */

#include <iostream>
#include <cassert>
#include <cmath>

/**
 * @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)

XCode Output

错误输入

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
欢迎转载,转载请注明出处。


See also

Teddy van Jerry 的 个人主页
Teddy van Jerry 的 CSDN 导航页
Teddy van Jerry 的 GitHub 主页
Teddy van Jerry 的 博客主页

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值