OK tip number 1, when posting code if you use [code\ ... [/code\ round the code you're posting it will preserve the whitespace (indenting) and make it easier to read.
[html\ and [php\ also exist for those types of file.
OK some general comments, if you enforce the condition (b*b-4*a*c>0) then you will not complete the assignment correctly because it has asked you to solve the equation even for complex roots and complex roots occur when (b*b-4*a*c<0). If fact you wont even solve all the equations with non-complex roots because when (b*b-4*a*c==0) you will have 1 non-complex root but you have excluded it. This includes simple equations like y=(x+1)(x+1) which has the single root x = -1 but for which (b*b-4*a*c==0).
Are you familiar with j = sqrt(-1) (or i if you are a mathamatition), clearly you can not actually calculate this number but coupled with sqrt(a*b) = aqrt(a) * sqrt(b) it allows you to write sqrt(-a) = j * sqrt(a).
This is where the complex root solving comes in because once you have complex numbers of the form x + y*j (i.e. 3 + 4j) you can then solve the quadratic equation for any values of a, b and c.
When (b*b-4*a*c<0) this allows you to treat
-b +- sqrt(b*b-4*a*c) / 2a
as
-b / 2a +- j * sqrt(-(b*b-4*a*c)) / 2a
which is a complex solution
Right and now my comments on your code in bold below
-
#include "stdafx.h"
-
# include <iostream>
-
# include <math.h>
-
using namespace std;
-
double qUeq(double a, double b, double c);
- /* You could declare qUeq as static since the code is all in 1 file */
-
int main()
-
{
-
double a,b,c;
-
cout<<"Input a,b,c(b*b-4*a*c>0):";
-
cin>>a>>b>>c;
- /* OK but have you considered what will happen if some
-
idiot inputs a non-number for one of the values like for
-
instance "a" */
-
qUeq(a,b,c);
-
return 0;
-
}
-
double qUeq(double a, double b, double c)
- /* Is there any point in returning double from this
-
function when you only ever return 0. You could return
-
a bool status, true for OK false for error
-
(for instance if a = 0) */
-
{
-
double x1,x2;
-
double sqrtVal=sqrt(b*b-4*a*c);
- /* You have calculated sqrt(b*b-4*a*c) before you
-
have checked if it is possible to calculate it */
-
if (b*b-4*a*c>0)
-
{
-
x1=(-b+sqrtVal)/(2*a);
-
x2=(-b+sqrtVal)/(2*a);
- /* You have accidentally calculated the same value
-
twice when you wanted to calculate the + and minus
-
value. Not also that sqrtVal could be 0 in which case
-
you have only 1 root. Also if a=0 then these lines will
-
not work because you will try to divide by zero.*/
-
cout<<"x1="<<x1<<endl;
-
cout<<"x2="<<x2<<endl;
-
}
-
else
-
cout<<"Please input the correct numbers,and try again.:)"<<endl;
-
return 0;
-
}
On the whole not a bad first try, you need to handle the complex case though to properly complete your assignment.
You should create your self a test of test values to test your program with.
Include at least 1 equation with 2 real root, 1 equation with 1 real root and 1 equation with 2 complex roots.