In qSolv, r1 and r2 are local variables that stop existing when the function ends. Despite the fact that they share a name with two different variables declared in main, they are in no way related to them.
Is nobody gonna reply? T_T
The people who use this forum volunteer their own time to do so. Waiting 20 minutes to bump a thread because you didn't get a reply is a level of impatience we don't see here often. (And from your edit, I see you couldn't even wait that long for an answer.) You would do well not to display it again.
The variables r1 and r2 in your main function are local to your main function only. They are not visible to your qSolv function.
The variables r1 and r2 in your qSolv function are again just local to the qSolv function only and they are not visible to your main function. If you change these variables, the variables in main do not get changed.
Since you are trying to output the values of r1 and r2 from your main function, the compiler is warning you that you haven't as yet assigned any values to them.
Instead in your qSolv:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
double qSolv(double &a, double &b, double &c)
{
double r1, r2;
if ((pow(b,2) - (4*a*c)) < 0) {
std::cout<< "No real roots to this quadratic.";
std::cin.ignore();
return -1;
}
else {
r1 = (-b + sqrt(pow(b,2) - (4*a*c)))/(2*a);
r2 = (-b - sqrt(pow(b,2) - (4*a*c)))/(2*a);
}
std::cout << "Your roots are: " << r1 << " and " << r2; // You will have to include iostream in this file.
}
your program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
double a, b, c;
double r1, r2;
cout<< "Please enter your coefficients: ";
cin>> a >> b >> c;
qSolv(a, b, c);
//cout<< "Your roots are: " << r1 << " and " << r2;
cin.get();
return 0;
}
Yes it is. The solution I suggested is the simplest one with minimal changes to your code.
However, there are other, probably better ways to resolve such scope issues. One way is to pass r1 and r2 to your qSolv function by reference. (like your other variables).
#include <cmath>
#include <iostream>
bool qSolv(double a, double b, double c, double& r1, double& r2)
{
constdouble discriminant = b*b - 4*a*c;
if (discriminant < 0)
returnfalse;
r1 = (-b + std::sqrt(discriminant)) / (2 * a);
r2 = (-b - std::sqrt(discriminant)) / (2 * a);
returntrue;
}
int main()
{
double a, b, c;
std::cout << "Please enter your coefficients: ";
std::cin >> a >> b >> c;
double root1, root2;
if (qSolv(a, b, c, root1, root2))
std::cout << "Your roots are: " << root1 << " and " << root2 << '\n';
else
std::cout << "No real roots to this quadratic.\n";
}
You should also return values from functions which you promise will return values (such as your version of qSolv which should return a value of type double.) Don't put function definitions in header files unless they are inline.