C exercises and solutions: C if else logical operators (continued)


C if else logical operators exercises (con.)

3. Write C code to compute the real roots of the equation: ax2+bx+c=0.


The program will prompt the user to input the values of a, b, and c. It then computes the real roots of the equation based on the following rules:
-if a and b are zero=> no solution
-if a is zero=>one root (-c/b)
-if b2-4ac is negative=>no roots
-Otherwise=> two roots
The roots can be computed using the following formula:
x1=-b+(b2-4ac)1/2/2a
x=-b-(b2-4ac)1/2/2a


Solution

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main(int argc, char *argv[])
{
   
   float a;
   float b;
   float c;
   float delta;
   printf("Enter values of a b c separated by space:");
   scanf("%f %f %f",&a,&b,&c);
   if(a==0 && b==0)printf("No root");
   else if(a==0)printf("The equation has only one root:%.2f",-b/c);
   else {
        delta=b*b-4*a*c;
        if(delta<0) printf("No root");
        else printf("The equation has two roots:x=%.2f",-b+sqrt(b*b-4*a*c)/(2*a));printf(",x1=%.2f",-b-sqrt(b*b-4*a*c)/(2*a));
        }              
 
   printf("\n");
 
   system("PAUSE");    
   return 0;

}


Comments

Aruj comment

 Aruj

Thank you


2018-01-12
ler comment

 ler

I did it! thank you!


2015-05-28
Abhishek Verma comment

 Abhishek Verma

Hi i want to know that how "%.2f" works in printf and when it is used in c language.

Thank you.


2015-02-14



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.