quadratic.jl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env julia
  2. # File: quadratic.jl
  3. # Name: D.Saravanan
  4. # Date: 15/08/2021
  5. """ Program to solve for the roots of a quadratic equation """
  6. using Printf
  7. function roots(a::Float64, b::Float64, c::Float64)
  8. # calculate discriminant
  9. discriminant = b^2 - 4*a*c
  10. # solve for the roots, depending upon the value of the discriminant
  11. if (discriminant > 0)
  12. x1 = (-b + sqrt(discriminant))/(2*a)
  13. x2 = (-b - sqrt(discriminant))/(2*a)
  14. @printf("This equation has two real roots: x1 = %.2f and x2 = %.2f\n", x1, x2)
  15. elseif (discriminant == 0)
  16. x1 = (-b)/(2*a)
  17. @printf("This equation has two identical real roots: x1 = x2 = %.2f\n", x1)
  18. else
  19. real_part = (-b)/(2*a)
  20. imag_part = sqrt(abs(discriminant))/(2*a)
  21. @printf("This equation has complex roots: x1 = %.2f + i%.2f and x2 = %.2f - i\
  22. %.2f\n", real_part, imag_part, real_part, imag_part)
  23. end
  24. end
  25. # prompt the user for the coefficients of the equation
  26. println("This program solves for the roots of a quadratic equation")
  27. print("Enter the coefficients a, b, and c: ")
  28. a, b, c = [parse(Float64, x) for x in split(readline())]
  29. # print the coefficients
  30. @printf("The coefficients a, b, and c are: %.1f, %.1f, %.1f\n", a, b, c)
  31. roots(a, b, c)