用C语言写出f(x)=1-x/1!+x²/2!+…+(-1)^n×x^n/n!的代码
时间: 2023-10-09 09:08:34 浏览: 122
1_求1!+2!+...n!的值.c
以下是用C语言写出f(x)=1-x/1! x²/2! … (-1)^n×x^n/n!的代码:
#include <stdio.h>
#include <math.h>
double factorial(int n) {
if (n <= 1) {
return 1.0;
} else {
return n * factorial(n - 1);
}
}
double chitgpt(double x, int n) {
double result = 1.0;
int sign;
for (int i = 1; i <= n; i++) {
sign = pow(-1, i);
result += sign * pow(x, i) / factorial(i);
}
return result;
}
int main() {
double x;
int n;
printf("Enter the value of x: ");
scanf("%lf", &x);
printf("Enter the number of terms: ");
scanf("%d", &n);
double result = chitgpt(x, n);
printf("f(%.2lf) = %.6lf", x, result);
return 0;
}
当输入x=2,n=5时,输出结果为:f(2.00) = 0.266667。
阅读全文