请编写函数fun,其功能是:计算下面数列前n项的和,(设n=50,x=0.5),将结果四舍五入保留4位小数。 cos(x)/x,cos(2x)/2x,cos(3x)/3x, …… ,cos(nx)/(nx), …… (其中,cos为余弦函数;n=1,2,3…)
下面是一个实现函数fun的C语言代码,该代码使用循环计算前n项的和,并使用round函数对结果进行四舍五入保留4位小数:
#include <stdio.h>
#include <math.h>
double fun(int n, double x) {
double sum = 0;
int i;
for(i = 1; i <= n; i++) {
sum += cos(i * x) / (i * x);
}
return round(sum * 10000) / 10000.0;
}
int main() {
int n = 50;
double x = 0.5;
double result = fun(n, x);
printf("The sum of the series is: %.4f\n", result);
return 0;
}
在主函数中,我们将n设置为50,x设置为0.5,然后调用fun函数计算数列的前n项之和。最后,我们使用printf函数打印结果,保留4位小数。
注意,在本例中,我们使用了math.h库中的cos函数和round函数。cos函数是用于计算余弦值的标准函数,而round函数可以将浮点数四舍五入到指定的小数位数。