Skip to main content

Quadratic equation roots in FORTRAN

Short answer

Read coefficients a, b, c. If a=0, output 'not quadratic'. Compute discriminant D=b²-4ac. For D>0, real distinct roots (-b±√D)/(2a); D=0, real equal root -b/(2a); D<0, complex roots with real part -b/(2a) and imaginary part √(-D)/(2a).

Write a FORTRAN program to display nature of roots of a quadratic equation. Calculate and display the roots, if they are real and equal. (Solve quadratic equation and display roots in proper format.)

Method. For a x² + b x + c = 0, the discriminant is D = b² − 4ac.

  • D > 0: two real, distinct roots (−b ± √D) / 2a.
  • D = 0: real and equal roots, x = −b / 2a.
  • D < 0: complex roots, −b/2a ± i √(−D)/2a.
  • a = 0: not a quadratic equation.
      PROGRAM QUAD
      REAL A, B, C, D, X1, X2, RP, IP
      PRINT *, 'ENTER A, B, C'
      READ *, A, B, C
      IF (A .EQ. 0.0) THEN
         PRINT *, 'NOT A QUADRATIC EQUATION'
         STOP
      END IF
      D = B*B - 4.0*A*C
      IF (D .GT. 0.0) THEN
         PRINT *, 'ROOTS ARE REAL AND DISTINCT'
         X1 = (-B + SQRT(D)) / (2.0*A)
         X2 = (-B - SQRT(D)) / (2.0*A)
         WRITE(*,10) X1, X2
      ELSE IF (D .EQ. 0.0) THEN
         PRINT *, 'ROOTS ARE REAL AND EQUAL'
         X1 = -B / (2.0*A)
         WRITE(*,20) X1
      ELSE
         PRINT *, 'ROOTS ARE COMPLEX'
         RP = -B / (2.0*A)
         IP = SQRT(-D) / ABS(2.0*A)
         WRITE(*,30) RP, IP, RP, IP
      END IF
   10 FORMAT(' X1 = ', F8.3, '   X2 = ', F8.3)
   20 FORMAT(' X1 = X2 = ', F8.3)
   30 FORMAT(' X = ', F8.3, ' + ', F8.3, 'I  AND  ',
     1       F8.3, ' - ', F8.3, 'I')
      STOP
      END

Sample results (worked by hand)

  • a, b, c = 1, −5, 6: D = 1, roots X1 = 3.000 X2 = 2.000.
  • a, b, c = 1, −6, 9: D = 0, roots X1 = X2 = 3.000.
  • a, b, c = 1, 2, 5: D = −16, roots −1.000 ± 2.000 i.

The format codes F8.3 print a real in 8 columns with 3 digits after the decimal point.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →