ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมที่จะหาผลรวมของชุดที่ 1 – x^2/2! + x^4/4! … ไม่เกินเทอมที่ n
สำหรับสิ่งนี้เราจะได้ค่า x และ n งานของเราคือการคำนวณผลรวมของอนุกรมที่กำหนดไม่เกินเงื่อนไขที่กำหนด สามารถทำได้ง่ายๆ ด้วยการคำนวณแฟคทอเรียลและใช้ฟังก์ชันกำลังมาตรฐานในการคำนวณกำลัง
ตัวอย่าง
#include <math.h>
#include <stdio.h>
//calculating the sum of series
double calc_sum(double x, int n){
double sum = 1, term = 1, fct, j, y = 2, m;
int i;
for (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 = sum + m;
y += 2;
}
return sum;
}
int main(){
double x = 5;
int n = 7;
printf("%.4f", calc_sum(x, n));
return 0;
} ผลลัพธ์
0.3469