**Explain yourself**with reStructured Text, embedded code, graphs, charts, and LaTeX–style math. Join Siafoo Now or Learn More

# Simple Quadratic Equation Solver 0

Updated over 10 years ago (24 Jul 2008 at 04:51 PM)
recent activity

In Brief | An example Fortran program that given the coefficients, a, b and c of a quadratic equation , will solve for the roots using the well known quadratic formula |

Language | Fortran |

# 's

` 1! ---------------------------------------------------`

2! Author:

3! Dr. Ching-Kuang Shene

4! Department of Computer Science

5! Michigan Technological University

6!

7! Solve Ax^2 + Bx + C = 0 given B*B-4*A*C >= 0

8! Now, we are able to detect the following:

9! (1) unsolvable equation

10! (2) linear equation

11! (3) quadratic equation

12! (a) distinct real roots

13! (b) repeated root

14! (c) no real roots

15! ---------------------------------------------------

16

17PROGRAM QuadraticEquation

18 IMPLICIT NONE

19

20 REAL :: a, b, c

21 REAL :: d

22 REAL :: root1, root2

23

24! read in the coefficients a, b and c

25

26 READ(*,*) a, b, c

27 WRITE(*,*) 'a = ', a

28 WRITE(*,*) 'b = ', b

29 WRITE(*,*) 'c = ', c

30 WRITE(*,*)

31

32 IF (a == 0.0) THEN ! could be a linear equation

33 IF (b == 0.0) THEN ! the input becomes c = 0

34 IF (c == 0.0) THEN ! all numbers are roots

35 WRITE(*,*) 'All numbers are roots'

36 ELSE ! unsolvable

37 WRITE(*,*) 'Unsolvable equation'

38 END IF

39 ELSE ! linear equation

40 WRITE(*,*) 'This is linear equation, root = ', -c/b

41 END IF

42 ELSE ! ok, we have a quadratic equation

43 d = b*b - 4.0*a*c

44 IF (d > 0.0) THEN ! distinct roots?

45 d = SQRT(d)

46 root1 = (-b + d)/(2.0*a) ! first root

47 root2 = (-b - d)/(2.0*a) ! second root

48 WRITE(*,*) 'Roots are ', root1, ' and ', root2

49 ELSE IF (d == 0.0) THEN ! repeated roots?

50 WRITE(*,*) 'The repeated root is ', -b/(2.0*a)

51 ELSE ! complex roots

52 WRITE(*,*) 'There is no real roots!'

53 WRITE(*,*) 'Discriminant = ', d

54 END IF

55 END IF

56

57END PROGRAM QuadraticEquation

An example Fortran program that given the coefficients, `a`, `b` and `c` of a quadratic equation
, will solve for the roots using the well known quadratic formula

Add a Comment