Lucas
Lucas

Reputation: 15

Error in 2º equation roots coding in Fortran

Today I started coding equations and algebraic expressions using Fortran (I'm using gfortran in Debian(Parrot-home OS) and Geany).

The problem is, I code on the same way(or equal) to the mode I see on internet, and I get only a wrong root to x' and x''.

program equacao2grau
    real delta, a, b, c, x, x2
    complex sqrt
    print*, "This program calc 2º equations"
    print*, "Give the values 'A', 'B'e 'C'"
    read*, a         !Getting values
    read*, b         !       for
    read*, c         !resolution
    if (a /= 0) then          !if 'a' be different of 0
        delta = b**2 - 4*a    !do delta
    end if

    print*, delta = b**2 - 4*a*c

    if (a .EQ. 0) then
        stop
    end if
        if (delta .EQ. 0) then
            print*, "The value is", (-b / 2*a)
                stop
        end if
        if (delta .GT. 0) then
            print*, "The roots are", -b + sqrt(delta) / 2*a
            print*, "e", -b - sqrt(delta) / 2*a
            stop
        end if
end

I know, it is incomplete, but I'm demotivated with don't find any correct result.

Things I researched:

Upvotes: 1

Views: 107

Answers (1)

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 8556

You are missing brackets in the expressions.

-b + sqrt(delta) / 2*a

Should be:

(-b + sqrt(delta)) / (2*a)

And same for the other roots.

Edit Also, as pointed by @albert, you omitted c in the formula of delta. Moreover, as said by @IanBush, the declaration of complex sqrt must be removed. And always use implicit none.

Upvotes: 1

Related Questions