Tính tổng chuỗi: 1 - x²/2! + x⁴/4! - x⁶/6! + ... đến n số hạng. Dùng hàm pow() cho lũy thừa và tính giai thừa trong vòng lặp.
Ví dụ
#include <math.h>
#include <stdio.h>
double calc_sum(double x, int n) {
double sum = 1, term = 1, fct, j, y = 2, m;
for (int i = 1; i < n; i++) {
fct = 1;
for (j = 1; j <= y; j++)
fct = fct * j;
term = term * (-1);
m = term * pow(x, y) / fct;
sum += m;
y += 2;
}
return sum;
}
int main() {
double x = 5;
int n = 7;
printf("%.4f", calc_sum(x, n));
return 0;
}
Kết quả
0.3469