我如何替换 pow()?

0 c c++

如何在我的代码中在两种情况下替换 pow() 函数?

我认为这可以通过 for 循环来完成

#include <iostream>
#include <cmath>

using namespace std;

int main(){
double a, b, h, PI = 3.141592;
int n;

cin >> a >> b >> h >> n;

for (double x = a; x <= b; x += h) {
    double ans = 1, y;
    for (int k = 0; k <= n; k++) {
        ans *= cos(k * PI / 4) * pow(x, k);

        for (int i = 2; i <= k; i++) {
            ans /= i;
        }

    }
    y = pow(exp(cos(x * sin(PI / 4))), x * cos(PI / 4));
    cout << ans << " " << y << " " << fabs(y-ans) << endl;
}

return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的任务条件

Mar*_*k R 5

  1. 不要将所有内容都写在 main 中。
  2. 定义double S(double x, int n)double U(double x)
  3. sum 的每个元素都可以根据前一个元素计算。
  4. cos(k * M_PI / 4) 具有重复值,因此可以存储在表中。
double S(double x, int n)
{
    double a = 1;
    double s = a;
    constexpr double q = std::cos(M_PI / 4);
    constexpr double cos_val[]{ 1, q, 0, -q, -1, -q, 0, q };
    for (int k = 1; k <= n; ++k) {
        a *= x / k;
        s += cos_val[k & 7] * a
    }
    return s;
}
Run Code Online (Sandbox Code Playgroud)