15,399,959 members
Articles / Programming Languages / C++
Alternative
Tip/Trick
Posted 10 Jun 2010

36.1K views
3 bookmarked

# A simple program to solve quadratic equations with

Rate me:
8 Nov 2010CPOL
Simple and prints imaginary roots too!float a,b,c,x1,x2,d,dsq;printf("ax^2 + bx + c = 0");printf("\nEnter a,b,c separated by commas : \n");scanf("%f,%f,%f",&a,&b,&c);d = b*b-(4*a*c);if(d>=0){dsq=sqrt(d);x1 = (-b+dsq)/(2*a);x2 = (-b-(dsq))/(2*a);printf("\nRoot 1 : %f\nRoot 2...
Simple and prints imaginary roots too!
C#
```float a,b,c,x1,x2,d,dsq;
printf("ax^2 + bx + c = 0");
printf("\nEnter a,b,c separated by commas : \n");
scanf("%f,%f,%f",&a,&b,&c);
d = b*b-(4*a*c);
if(d>=0)
{
dsq=sqrt(d);
x1 = (-b+dsq)/(2*a);
x2 = (-b-(dsq))/(2*a);
printf("\nRoot 1 : %f\nRoot 2 : %f",x1,x2);
}
if(d<0)
{
d = ((4*a*c)-pow(b,2))/(2*a);
printf("\nRoot 1 : %f+%fi",((-b)/(2*a)),d);
printf("\nRoot 2 : %f-%fi",((-b)/(2*a)),d);}```

## Share

 Student India
No Biography provided

 First Prev Next
 You have missed one VISWESWARAN199814-Jun-16 20:18 VISWESWARAN1998 14-Jun-16 20:18
 Reason for my vote of 2 Can crash too ! YvesDaoust8-Nov-10 23:27 YvesDaoust 8-Nov-10 23:27
 thats the most basic rule in the book Sherylee8-Nov-10 22:38 Sherylee 8-Nov-10 22:38
 1) It doesn't matter what the real world quadratic equations... Ron Beyer8-Nov-10 4:34 Ron Beyer 8-Nov-10 4:34
 Thank you for the suggestion.. I do not wish to be rude. If... Anshul R8-Nov-10 0:13 Anshul R 8-Nov-10 0:13
 Reason for my vote of 2 Inefficient and does not handle divi... Andrew Phillips7-Nov-10 15:19 Andrew Phillips 7-Nov-10 15:19
 This is better than the others as you avoid the domain error... Andrew Phillips7-Nov-10 15:14 Andrew Phillips 7-Nov-10 15:14
 This is better than the others as you avoid the domain error in sqrt(). A couple of things: - pow(b, 2) is better written as b*b - it's probably better not to evaluate sqrt(d) twice - the original returned two floats, you should return an error instead of complex numbers
 Last Visit: 31-Dec-99 18:00     Last Update: 19-Aug-22 1:37 Refresh 1