【入門】洛谷P1024:一元三次方程求解 兩種解法

解法一

在[-100,100]大區(qū)間中遞進循環(huán),由于根與根之差的絕對值>=1,即在間隔為1的前開后閉區(qū)間里最多有一個根,從[i,i+1]中二分查找符合零點定理的解(題目中的提示即為零點定理,這里的閉區(qū)間是為了最后一個數(shù)100這個特殊情況)。
二分查找,精度設為0.001(也就是(high-low)<0.001才二分結(jié)束,小數(shù)點后第三位是唯一確定的,這時候就可以唯一確定一個精度為0.01的解了)

#include <stdio.h>
#define e(x) (d + (x) * (c + (x) * (b + a * (x))))

int main() {
    double a, b, c, d, low, high, mid;
    int index, resNum = 0;

    scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
    for (index = -100; index < 100; index++) {
        low = index;
        high = index + 1;
        if (e(low) == 0) {  // 這里覆蓋不到100這個數(shù)
            printf("%.2lf ",low);
            resNum++;
        } 
        else if (e(low)*e(high) < 0) {
            while ((high-low) >= 0.001 ) {  // 100這個特殊情況交由二分查找來解決
                mid = (low + high) / 2.0;
                if (e(low)*e(mid) <= 0) {
                    high = mid;
                } 
                else {
                    low = mid;
                }
            }
            printf("%.2lf ", low);
            resNum++;
        }
        if (resNum == 3) break; // 節(jié)約時間
    }

    return 0;
}

解法二

暴力輪詢求解,通過小數(shù)點后兩位鎖定解所在的較小的一個范圍,然后再次循環(huán),間隔為0.0001,即可鎖定精度為0.01的解。

#include <stdio.h>
#define e(x) (d + (x) * (c + (x) * (b + a * (x))))

int main() {
    double a, b, c, d, index_dec, index;
    int s = 0;

    scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
    for (index = -100; index < 100; index += 0.01) {
        if (e(index)*e(index + 0.01) <= 0) {
            for (index_dec = index; index_dec <= (index + 0.01); index_dec += 0.0001) {
                if (e(index_dec)*e(index_dec + 0.0001) <= 0) {
                    printf("%.2lf ", index_dec);
                    s++;
                    if (s == 3) {
                        break;  // 退出內(nèi)層For循環(huán)
                        break;  // 退出外層For循環(huán)
                    }
                }
            }
        }
    }

    return 0;
}

\color{red}{|-Cheng FengPoLang- | - QianChengSiJin-|}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容