不明白为什么第二个测试点过不去
查看原帖
不明白为什么第二个测试点过不去
99452
BDICOMENOW楼主2022/6/27 18:48

##2测试点:

in:1 -4.65 2.25 1.4

output:-0.35 1.00 4.00

问题点:特别是 1.00和4.00这两个点,这两个点带入函数f(1)和f(4)也不等于0呀,为什么我的程序不等于0?我自己把

double f(double x) { x = 1时
    cout << a * (x*x*x) << endl; //x=1时,结果为1
    cout << b * (x*x) << endl;//x=1时,结果为-4.65
    cout << c * x << endl; //x=1时,结果为2.25
    cout << d << endl;//x=1时,结果为1.4
    cout << a * (x*x*x) + b * (x*x) + c * x + d << endl; //但是计算结果却不是0,为什么,到底哪里错了?

    return a * x*x*x + b * x*x + c * x + d;
}

下面为完整程序:

#include<cstdio>
#include<iostream>
#include<cmath>//引入头文件 
#include<algorithm>
#include<string>
using namespace std;
#pragma warning(disable:4996)



double a, b, c, d;

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


int main()
{
    cin >> a >> b >> c >> d;
    double l = -100, r = 100;
    for (double i = l; i < r; i++) {
        if (f(i) == 0) {
            printf("%.2f ", i);
            continue;
        }
        if (f(i)*f(i + 1) < 0) {
            double starttmp = i, endtmp = i + 1;
            for (int j = 0; j < 60; j++) {
                double mid = (starttmp + endtmp) / 2;
                if (f(mid) == 0) {
                    printf("%.2f ", mid);
                    break;
                }
                else if (f(mid) < 0)
                    starttmp = mid + 0.01;
                else if (f(mid) > 0)
                    endtmp = mid - 0.01;
            }
        }

    }

    return 0;//养成好习惯,返回0
}
2022/6/27 18:48
加载中...