c++ wrong result with type double
my code solves cubic equations with binary search, I have an example of input and output, but results doesn't match. for example input: 1 -3 3 -1, output: 1.000000, but instead of 1.000000 it gives me 1.000017, it should have 6 numbers after the point
code:
#include
#include
using namespace std;
double f(double x, double a, double b, double c, double d) {
return a*x*x*x + b*x*x + c*x + d;
}
int main() {
double a, b, c, d;
cin >> a >> b >> c >> d;
double left = -10000.0, right = 10000.0;
for (int i=0; i<100; i++) {
double mid = left + (right-left) / 2.0;
double fmid = f(mid, a, b, c, d);
double fleft = f(left, a, b, c, d);
if (fleft * fmid < 0) right = mid;
else left = mid;
}
cout << fixed << setprecision(6) << left;
return 0;
}