📄 no.4.c
字号:
#include "stdio.h"
#include "conio.h"
#define ROOT_PRECISION 10e-5
#define SEARCH_PRECISION 10e-2
float func1(float x)
{
return (x*x*x - x - 1);
}
float func2(float x)
{
return (x*x*x - 3*x - 1);
}
float dimidiate(float a, float b, float (*f)(float x))
{
float x;
while (b - a > ROOT_PRECISION) {
x = (a + b) / 2;
if ( f(a)*f(x) > 0 ) {
a = x;
}
else {
b = x;
}
}
return x;
}
float forIncrease(float a, float b, float (*f)(float x))
{
float x;
float temp = b - a;
int n = 0, i;
do {
temp = temp / 2;
++n;
}while (temp > ROOT_PRECISION);
for (i = 0; i < n; i++) {
x = (a + b) / 2;
if ( f(a)*f(x) > 0 ) {
a = x;
}
else {
b = x;
}
}
return x;
}
int searchRoots(float a, float b, float (*f)(float x), float* root)
{
float newA, newB;
float x;
int n = 0;
for (newA = newB = a; newB <= b; newA = newB, newB += SEARCH_PRECISION) {
if (f(newA) * f(newB) < 0) {
x = dimidiate(newA, newB, func1);
root[n++] = x;
}
}
return n;
}
int main()
{
float root[3];
float x, xx;
int n, i;
n = searchRoots(-8, 8, func2, root);
printf("FUNCTION (x*x*x-3*x-1=0) have %d roots in (-8, 8)\n", n);
for (i = 0; i < n; i++) {
printf("root[%d] = %.5f\n", i+1, root[i]);
}
printf("\nFUNCTION (x*x*x-x-1=0)\n");
x = dimidiate(1, 1.5, func1);
printf("dimidiate method_1: root = %.5f\n", x);
xx = forIncrease(1, 1.5, func1);
printf("dimidiate method_2: root = %.5f\n", xx);
getch();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -