Write the definition of a function named quadratic that receives three double parameters a , b , c . If the value of a is 0 then the function prints the message "no solution for a=0" and returns. If the value of "b squared" – 4ac is negative, then the code prints out the message "no real solutions" and returns. Otherwise the function prints out the largest solution to the quadratic equation. The formula for the solutions to this equation can be found here: Quadratic Equation on Wikipedia.
This is what I have so far and every time I try to submit it, it always says that it's wrong. I don't know what's wrong with my code.
double quadratic(double a, double b, double c)
{
double dis = b * b - 4 * a * c;
if (a = 0)
cout << "no solution for a=0";
return;
if ((sqrt(b) * 4 * a * c) < 0)
cout << "no real solutions";
return;
elsedouble x = (-b+sqrt(b*b-4*a*c))/(2*a);
double y = (-b-sqrt(b*b-4*a*c))/(2*a);
if (x > y)
{
cout << x;
return;
cout << y;
return;
}
}
If you follow the instructions accordingly, the first thing to check for in the function is the value of a, so before Line 3, Line 4 should have appeared and its like this if (a==0) {std::cout<<"no solution for a=0"<<std::endl; return;}. else if (a!=0) then Line 3 can appear.
Again if value of dis<0 then print a message and return immediately to main().
ELSE continue with the rest and return the result.
if ((sqrt(b) * 4 * a * c) < 0)
cout << "no real solutions";
return;
First, the wrong condition is tested. It should be if (dis < 0)
Second, the if statement controls just a single statement, it requires braces around the following statements, in order to control the entire block.
1 2 3 4 5
if (dis < 0)
{
cout << "no real solutions";
return;
}
The variable dis can also be used in the other calculation:
double x = (-b+sqrt(b*b-4*a*c))/(2*a);
could be simplified to
double x = (-b + sqrt(dis)) / (2*a);
There's no need to calculate both roots, x and y, as the requirements state " the function prints out the largest solution" therefore y which is the smaller root is not needed.
One more thing, there's no need for an else part to the if statement. Because the return statement is executed within the if block, the function terminates at that point and does not execute any of the remaining code.