I am trying to create a program in C++ that will use the bisection method on a cubic function to find a root of that cubic function. Now I have this:
#include <iostream>
#include <cmath>
using namespace std;
int functie(double a,double b,double c,double d,double x){
double y;
y = (a*x*x*x + b*x*x + c*x + d);
return y;
}
int main(){
int a,b,c,d;//no comment
cout << "enter of form: ax^3 + bx^2 + cx + d (integers)" << endl << "a: ";
cin >> a;
cout << endl << "b: ";
cin >> b;
cout << endl << "c: ";
cin >> c;
cout << endl << "d: ";
cin >> d;
double min, max, temp;
min = -100;
max = 108.54267542;
while(functie(a,b,c,d,max) == 0 ||functie(a,b,c,d,min) == 0 ){
temp = (max + min)/2;
if(functie(a,b,c,d,min) < 0 && functie(a,b,c,d,temp) < 0 || functie(a,b,c,d,min) > 0 && functie(a,b,c,d,temp) > 0){
min = temp;
} else {max = temp;}
}
cout << min << endl;
cout << max << endl;
cout << temp << endl;
system("pause");
return 0;
}
but it doesn’t work; the cout’s at the end of the program only output the input values.
(and in case you were wondering why my max value is so weird, is to prevent that when max is +100 and the root is at 0, then the program will crash…)
So if you have got some time and want to check this, thank you.
Of course it’s wrong. On this line:
The loop will execute only when the value returned from
functieis zero. The values ofmaxandminshould never change.And you have declared
functielike this:You’re returning (and you should) a
doublevalue fromfunctie, but because of the definition it’s cast into anint.