求助一道关于阶乘的题
cos(x)=1-(x^2/2!)+(x^4/4!)-(x^6/6!)...............(x为弧度,计算精度为1e-6)这个怎么编程序呢
input"x" to x
s=1
f=1
n=2
d=-1
do while x^n/f>=1e(-6)
f=f*(2*n-2)*(2*n-3)
s=s+(x^(2*n-2)/f)*d
d=-d
n=n+1
enddo
?s
我这样编的好像错了哦???
程序代码:
/*
SinX=X/1!-X^3/3!+X^5/5!-X^7/7!+……+(-1)n+1*X^(2n-1)/(2n-1)!
*/
#include <stdio.h>
double pow(const double x, const int n);
double factorial(const int n);
int main(int argc, char* argv[])
{
double x; // 弧度
int n; // 求值项数
int sign = 0; // 正负号标志
double sin = 0.0; // 计算结果
double temp;
int i;
if (argc < 3)
{
printf_s("格式: %s x n\n", argv[0]);
printf_s("其中,x是弧度制角度,n是多项式项数,n=0不计算,结果为零。\n");
printf_s("举例 Sin 1.5 20\n");
return -1;
}
sscanf_s(argv[1], "%lf", &x);
sscanf_s(argv[2], "%d", &n);
if (n < 0)
{
printf_s("错误:n = %d\n", n);
return -2;
}
for (i = 1; i <= n; ++i)
{
sign = !sign;
temp = pow(x, 2 * i - 1) / factorial(2 * i - 1);
if (sign)
{
sin += temp;
}
else
{
sin -= temp;
}
}
printf_s("Sin(%.2f) = %.16f\n", x, sin);
return 0;
}
// 计算x^n
double pow(const double x, const int n)
{
int i;
double ret_value = 1.0;
for (i = 0; i < n; ++i)
{
ret_value *= x;
}
return ret_value;
}
// 计算n!
double factorial(const int n)
{
int i;
double ret_value = 1.0;
for (i = 1; i <= n; ++i)
{
ret_value *= (double)i;
}
return ret_value;
}

程序代码:
*-----------------------------------
* 题目:运用级数收敛求余弦值
* 级数公式:Cos(x) = 1 - x^2 / 2! + x^4 / 4! - ……+ (-1)^n·x^2n / (2n)!
* 结束条件:末项值 < 1e(-6)
* 备注:1.因VFP有指数运算符^,所以无需自编幂运算函数
* 2.注意控制输入的弧度值不要超过60,此时级数项至n=85,将导致阶乘溢出双精度数范围。
*-----------------------------------
SET DECIMALS TO 18
CLEAR
Input "请输入弧度 x = " to nAngle
nCosine = 0.0 && 余弦初值
nIndex = 0 && n计数器
nSign = 1 && 正负号
DO WHILE .T.
nItem = nAngle ^ (2 * nIndex) / Factorial(2 * nIndex) && 计算每项,n=0开始
nCosine = nCosine + nSign * nItem && 把每项的值累加到结果
IF nItem <= 1E-6 && 当某项的绝对值满足结束条件时终止循环
EXIT
ENDIF
nIndex = nIndex + 1
nSign = -nSign && 反转每项的正负号
ENDDO
? "Cos(", nAngle, ") = ", nCosine
RETURN
* 求自然数n的阶乘
FUNCTION Factorial(n)
LOCAL nIndex, nReturnVal
* 如果n是数值型数据且大于等于零则进行运算,否则返回零(正常阶乘值不会等于零的)
IF (VARTYPE(n) == "N") .AND. (n >= 0)
nReturnVal = 1
FOR nIndex = 1 TO n
nReturnVal = nReturnVal * nIndex
NEXT
ELSE
nReturnVal = 0
ENDIF
* 计算结果返回到调用处
RETURN nReturnVal
ENDFUNC
