Click here to Skip to main content
15,399,959 members
Articles / Programming Languages / C++
Posted 10 Jun 2010

Tagged as


3 bookmarked

A simple program to solve quadratic equations with

Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
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!
float a,b,c,x1,x2,d,dsq;
printf("ax^2 + bx + c = 0");
printf("\nEnter a,b,c separated by commas : \n");
d = b*b-(4*a*c);
x1 = (-b+dsq)/(2*a);
x2 = (-b-(dsq))/(2*a);
printf("\nRoot 1 : %f\nRoot 2 : %f",x1,x2);
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);}


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Anshul R
India India
No Biography provided

Comments and Discussions

SuggestionYou have missed one Pin
VISWESWARAN199814-Jun-16 20:18
professionalVISWESWARAN199814-Jun-16 20:18 
GeneralReason for my vote of 2 Can crash too ! Pin
YvesDaoust8-Nov-10 23:27
MemberYvesDaoust8-Nov-10 23:27 
Generalthats the most basic rule in the book Pin
Sherylee8-Nov-10 22:38
MemberSherylee8-Nov-10 22:38 
General1) It doesn't matter what the real world quadratic equations... Pin
Ron Beyer8-Nov-10 4:34
professionalRon Beyer8-Nov-10 4:34 
GeneralThank you for the suggestion.. I do not wish to be rude. If... Pin
Anshul R8-Nov-10 0:13
MemberAnshul R8-Nov-10 0:13 
GeneralReason for my vote of 2 Inefficient and does not handle divi... Pin
Andrew Phillips7-Nov-10 15:19
MemberAndrew Phillips7-Nov-10 15:19 
GeneralThis is better than the others as you avoid the domain error... Pin
Andrew Phillips7-Nov-10 15:14
MemberAndrew Phillips7-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

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.