Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with program logic

Status
Not open for further replies.

Dukelord123

Technical User
Nov 27, 2010
4
DE
I am trying to write a program to solve a quadratic equation.If the value of (B**B-4*A*C) is 0 or negative, it should immediately write that "The roots of the equation is complex", but if positive, it should evaluate. It seems my logic is faulty cos no matter what values I give for A,B & C, I keep getting "The roots of the equation are complex". Please see code and results below. Thanks.



PROGRAM QUADEQN
INTEGER A,B,C
REAL D,X,Y,Q
D=(B**2-4*A*C)
Q=SQRT(D)
READ(*,5)A
READ(*,6)B
READ(*,7)C
IF(B**2-4*A*C)10,15,20
X=(-B+Q)/(2*A)
Y=(-B-Q)/(2*A)
20 WRITE(*,25)X,Y
5 FORMAT(I2)
6 FORMAT(I2)
7 FORMAT(I2)
10 WRITE(*,*)'THE ROOTS OF THE QUADRATIC EQUATION IS COMPLEX'
15 WRITE(*,*)'THE ROOTS OF THE QUADRATIC EQUATION IS COMPLEX'
25 FORMAT(/,'THE ROOTS OF THE EQN ARE',1X,F8.4,'AND',1X,F8.4)
STOP
END

**RESULT**

D:\Postgraduate\Programming\FORTRAN>gfortran quad.f

D:\Postgraduate\Programming\FORTRAN>a.exe
8
3
2
THE ROOTS OF THE QUADRATIC EQUATION IS COMPLEX
THE ROOTS OF THE QUADRATIC EQUATION IS COMPLEX

D:\Postgraduate\Programming\FORTRAN>

 
Hi Dukelord123

Well, it is better to read A, B and C before you calculate D=(B**2-4*A*C). Also to calculate X and Y before you jump in all cases over it as you do. The program below should work better.

Code:
      PROGRAM QUADEQN

      INTEGER A,B,C
      REAL D,X,Y,Q

      READ(*,5) A
      READ(*,5) B
      READ(*,5) C
5     FORMAT(I10)

      D = (B**2-4*A*C)
      IF(D.LT.0) GOTO 10
      
      Q = SQRT(D)
      X = (-B+Q)/(2*A)
      Y = (-B-Q)/(2*A)

      WRITE(*,25) X,Y
25    FORMAT(/,'THE ROOTS OF THE EQN ARE',1X,F8.4,'AND',1X,F8.4)
      GOTO 90
	
10    WRITE(*,*) 'THE ROOTS OF THE QUADRATIC EQUATION IS COMPLEX'

90    CONTINUE
      END
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top