⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 no.4.c

📁 中南大学C语言程序设计实习 1 实验一:C语言图形模式的设置 2 实习二:一元函数的图形绘制 3 实习三:二维图形的几何变换 4 实习四:非线性方程求根的二分法 5 实习五
💻 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 + -