I was asked to write a c++ function which determines the roots of a quadratic equation. The use of pointers in the function was a requirement and I've written the majority of the program but i can't seem to get the function to overwrite the values of x_1 and x_2. Everything else works flawlessly. I've spoken to the TA of my class and he can't seem to figure it out. I understand the concept behind pointers and can use them without a hitch when everything is in the main() program but not when I use a function. I feel like I'm missing something basic and i just can't seem to figure it out. Thanks for any assistance in advance.
#include <iostream> //stream objects (cin, cout...)
#include <cmath> //math libraries
#include <fstream> //file streaming objects (fstream...)
#include <string> //string manipulation
#include <iomanip> //formatting of output
usingnamespace std;
int quadratic(double a, double b, double c, double* x_1, double* x_2)
{
double disc=((b*b)-4*a*c);
if (disc>=0)
{
return(0);
*x_1=(-b+sqrt(disc))/(2*a);
*x_2=(-b-sqrt(disc))/(2*a);
}
else{
return(1);
*x_1=(-b)/(2*a);
*x_2=sqrt(-disc);
}
}
int main() {
int a;
double* x1=0;
double* x2=0;
a=quadratic(1,1,-15,x1,x2);
if (a==0){
cout<<"The real solutions are x= "<<x1<<"and x= "<<x2<<"\n";
}
else{
cout<<"The complex solutions are \n";
cout<<"x= "<<x1<<" + "<<x2<<"i\n";
cout<<"x= "<<x1<<" - "<<x2<<"i\n";
}
system("pause");
return 0;
} // closing brace
I get an output of 0000 for both x_1 and x_2, which derives from it's declaration earlier in the program. I'm using x^2+x-15 as my equation so i know it isn't working like it should. If i don't define an initial value for them, the program doesn't work at all.
I've also tried every combination of * and &, but nothing seems to change my problem.
When you return inside of your quadratic() function, the function ends and the rest of the work (assigning to the pointers) isn't performed. Just like in main(), don't return until the function is finished.