I am writing a C++ program for finding the real root, x for a cubic equation 〖ax〗^3+〖bx〗^2+ cx+d=0 where a≠0 and b=0.
Unfortunately, I could not output the "test case 1 & 4" (ps. sample output provided below link). Perhaps any logic syntax in my coding? Greatly appreciated if anyone could show me the correct way to do it.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main (){
int a , b, c , d;
double x , y;
double interval1, interval2;
bool stop;
b = 0;
x = 0;
stop = true;
cin >> a;
cin >> c;
cin >> d;
interval1 = a * pow(x , 3) + b * pow(x , 2) + c * x + d;
if (interval1 < 0){
interval2 = interval1 *-1;
}else{
interval2 = interval1;
interval1 = interval2 * -1;
}
while (stop=true){
x = interval1;
y = a * pow(x , 3) + b * pow(x , 2) + c * x + d;
if(y>0 && y<0.001){
break;
}else{
if (x<interval2) {
interval1 = x + 0.000001;
}else{
stop = false;
}
}
}
if (x==-0){
x = 0;
}
if(a==0){
cout << "NOT VALID" << endl;
}else{
std::cout << std::fixed << std::setprecision(3) << x;
}
return 0;
}
Your code is almost done. You need to improve some points.
Change int a , b, c , d;
to double a , b, c , d;
Change condition while (stop=true)
to while (stop==true)
I tested and it works as your example.