Please use C language and pointers to define a function to compute the integral of any unary function.
时间: 2024-05-08 16:15:05 浏览: 125
C-pointers-and-callback-function.zip_callback_function pointer_回
Here is an example implementation of a function to compute the integral of any unary function using C language and pointers:
```c
#include <stdio.h>
double integral(double (*f)(double), double a, double b, int n) {
double h = (b - a) / n; // width of each subinterval
double sum = 0.0; // initialize the sum
int i;
for (i = 0; i < n; i++) {
double x1 = a + i * h;
double x2 = a + (i + 1) * h;
double y1 = (*f)(x1);
double y2 = (*f)(x2);
double area = (y1 + y2) * h / 2.0;
sum += area;
}
return sum;
}
// example usage
double square(double x) {
return x * x;
}
int main() {
double a = 0.0;
double b = 1.0;
int n = 1000;
double result = integral(&square, a, b, n);
printf("Integral of x^2 from %g to %g with %d subintervals: %g\n", a, b, n, result);
return 0;
}
```
In this example, the `integral` function takes four arguments: a pointer to the unary function to integrate (`f`), the lower and upper bounds of integration (`a` and `b`, respectively), and the number of subintervals to use in the approximation (`n`). The function then computes the width of each subinterval (`h`), initializes the sum to 0, and iterates over the subintervals, computing the area under the curve for each and adding it to the sum. The final result is the sum of all the subinterval areas, which is returned by the function.
To demonstrate the usage of this function, the `square` function is defined as an example of a unary function to integrate, and is passed as a pointer to the `integral` function along with the bounds of integration and number of subintervals. The result is printed to the console.
阅读全文