Tính hàm sine
sử dụng công thức chuỗi
Chú ý trong CodeBlock nếu ta khai báo hàm sin, compiler sẽ báo lỗi vì đã có hàm sin trong thư viện .
#include <stdio.h>
#include <stdlib.h>
//forward
double sin(double x, int n);
int main()
{
const double pi = 3.14156178;
double result = sin(pi / 6.0, 10);
printf("%1.5f", result);
return 0;
}
//n is number of iteration, the greater n is, the more accurate of sin
double sin(double x, int n) {
double sinx = 0;
double xPower = x;
double factorial = 1;
for (int i = 0; i <= n; i++) {
int oneOrMinusOne = 1;
if (i % 2 == 1) {
oneOrMinusOne = -1;
}
sinx += oneOrMinusOne * xPower / factorial;
xPower = xPower * x * x;
factorial = factorial * (2 * i + 2) * (2 * i + 3);
}
return sinx;
}