计算余弦时,C ++总是获取-inf

尝试编写一个取值x并通过级数展开计算cos x的函数,我总是得到-inf,无论读入哪个值。

#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;

int fac(int n){
    return n == 0 || n == 1 ? 1 : n * fac(n-1);
}

int main(){
    double eps = 1e-15;
    double x;
    cin >> x;
    long double ak = 1, sn = 0;
    for(int k=1; abs(ak) > eps * abs(sn); k++){
        double sgn = k % 2 == 0 ? 1 : -1;
        sn += ak;
        ak = sgn * pow(x, 2 * k) / fac(2*k);
    }
    cout << setprecision(4) << setw(5) << "x" << setprecision(15) << setw(20) << "cos x" << endl;
    cout << setprecision(4) << setw(5)<< x << " " << setprecision(15) << setw(20) << sn << endl;
    cout << setw(26) << cos(x) << endl;
    return 0;
}

I debugged the code and at a certain point ak gets -inf. But why?