依次用n=8的复化梯形公式、n=4的复化辛普森公式计算定积分∫sinx/xdx从0到1用c语言代码实现
时间: 2023-06-12 11:06:27 浏览: 128
复化Simpson积分和复化梯形积分c语言程序源代码
5星 · 资源好评率100%
复化梯形公式的C语言代码如下:
```c
#include <stdio.h>
#include <math.h>
double f(double x) {
return sin(x) / x;
}
double trapezoidal(double a, double b, int n) {
double h = (b-a)/n;
double sum = 0.5*(f(a) + f(b));
for (int i = 1; i < n; i++) {
double x = a + i*h;
sum += f(x);
}
return h*sum;
}
int main() {
double a = 0.0, b = 1.0;
int n = 8;
double result = trapezoidal(a, b, n);
printf("The result is: %lf\n", result);
return 0;
}
```
复化辛普森公式的C语言代码如下:
```c
#include <stdio.h>
#include <math.h>
double f(double x) {
return sin(x) / x;
}
double simpson(double a, double b, int n) {
double h = (b-a)/n;
double sum = f(a) + f(b);
for (int i = 1; i < n; i += 2) {
double x = a + i*h;
sum += 4*f(x);
}
for (int i = 2; i < n-1; i += 2) {
double x = a + i*h;
sum += 2*f(x);
}
return (h/3)*sum;
}
int main() {
double a = 0.0, b = 1.0;
int n = 4;
double result = simpson(a, b, n);
printf("The result is: %lf\n", result);
return 0;
}
```
阅读全文