📄 no.6.c
字号:
#include "stdio.h"
#include "conio.h"
#include "math.h"
#define ROOT1_PRECISION 10e-3
#define ROOT2_PRECISION 10e-5
#define PI 3.1415926
enum {trapezia, rectangle};
float func1(float x)
{
return (sin(x) / x);
}
float func2(float x)
{
return (1 / (1 + x*x));
}
float integral(float a, float b, int n, float (*f)(float x), int type)
{
float h;
float r = 0;
float ox, x;
int i;
h = ( b - a ) / n;
x = a;
for (i = 1; i <= n; i++) {
ox = x;
x = x + h;
if (type)
r = r + f( (ox + x) / 2 );
else
r = r + ( f(ox) + f(x) ) / 2;
}
r = r * h;
return r;
}
float preciseIntegral(float a, float b, float (*f)(float x), int type, float precision)
{
float s1, s2;
int n = 10;
s2 = integral(a, b, n, f, type);
do {
n = n*n;
s1 = s2;
s2 = integral(a, b, n, f, type);
}while ( s2 - s1 > precision || s1 - s2 > precision);
return s1;
}
int main()
{
float s;
s = preciseIntegral(1, 2, func1, rectangle, ROOT1_PRECISION);
printf("func1 rectangle =%.3f\n", s);
s = preciseIntegral(1, 2, func1, trapezia, ROOT1_PRECISION);
printf("func1 trapezia =%.3f\n", s);
s = preciseIntegral(0, 1, func2, rectangle, ROOT2_PRECISION);
printf("func2 rectangle =%.5f\n", s);
s = preciseIntegral(0, 1, func2, trapezia, ROOT2_PRECISION);
printf("func2 trapezia =%.5f\n", s);
printf("PI / 4 =%.5f\n", PI / 4);
getch();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -