Real roots of a quadratic equation

From Programming In C

Exercise 2.1

Write a C program that reads in 3 real numbers, a, b and c that are the coefficients of a quadratic equation

ax2 + bx + c = 0

The program should calculate the 2 roots of the equation assuming that they are both real. Test your program with the following values

  1. a = 47.2, b = -148.1, c = 72.6
  2. a = -19, b = 67, c = 82

Check your answers with a demonstrator

Solution

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
 
int main(void)
{
 double a, b, c;
 double root1, root2;
 // First read in the first 3 co-efficients
 printf("Enter the co-efficients a, b, and c : ");
 scanf("%lf%lf%lf", &a,&b,&c );
 root1 = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*a);
 root2 = (-b - sqrt(b*b - 4.0*a*c)) / (2.0*a);
 printf("The roots of the equation %fx2+%fx+%f=0 are %f and %f\n",a,b,c,root1,root2);
 system("pause");
 return 0;
}

Comment
a = 47.2, b = -148.1, c = 72.6 gives roots of 2.529675 and 0.608037
a = -19, b = 67, c = 82 gives roots of -0.961638 and 4.487954


Next exercise

Return to the course summary

phy225: Course Details

general


compilers


2013-14 assessments


2012-13 assessments


past exam papers

  • 2010-11 (http://physics-database.group.shef.ac.uk/exampapers/2010-11/PHY225_10_11.pdf)
  • 2012-13 (http://physics-database.group.shef.ac.uk/exampapers/2012-13/PHY225-12-13.pdf)