luogu 1024

本文介绍了两种解决一元多项式方程求根的方法:一种是暴力枚举法,通过密集采样来逼近方程的实数解;另一种是更精确的二分查找法,用于寻找方程在指定区间内的实数解。这两种方法各有优缺点,暴力法简单直接但精度有限,而二分法则更加精确但实现复杂。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先介绍一种毒瘤的暴力(骗分过样例, 暴力出奇迹!!!~~~
只有50分

#include <cstdio>

using namespace std;

int a, b, c, d;

int read() {
    int f = 1, k = 0;
    char c = getchar();
    while(c < '0' ||  c > '9') {
        if(c == '-') {
            f = -1;
        }
        c = getchar();
    }
    while(c <= '9' && c >= '0') {
        k = k * 10 + c - '0';
        c = getchar();
    }
    return f * k;
}

int main() {
    a = read(), b = read(), c = read(), d = read();
    for(double i = -100; i <= 100.00; i += 0.01) {
        if(a * i * i * i + b * i * i + c * i + d < 0.0000001 && a * i * i * i + b * i * i + c * i + d > -0.0000001) {
            printf("%.2f ", i);
        }
    }
    return 0;
}

正解二分

#include <cstdio>
#include <iostream>

using namespace std;
const double j = 1e-6;

double a, b, c, d, cnt;

double f(double x) {
    return a * x * x * x + b * x * x + c * x + d;
}

int main() {
    cin>>a >>b >>c >>d;
    for(int i = -100; i <= 100; i ++) {
        if(cnt == 3) break;
        double x1 = i, x2 = i + 1;
        if(f(x1) == 0) {
            cnt++;
            printf("%.2lf ", x1);
            continue;
        }
        if(f(x1) * f(x2) >= 0) {
            continue;
        }
        while(x2 - x1 >= j) {
            double mid = (x1 + x2) / 2;
            if(f(x1) * f(mid) < 0) {
                x2 = mid;
            } else if(f(x2) * f(mid) < 0) {
                x1 = mid;
            }
        }
        cnt++;
        printf("%.2lf ", x1);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值