Sunday, March 11, 2018

Roots of quadratic equation

Roots of quadratic equation
Send Feedback

Write a program to calculate the roots of a given quadratic equation -

      a(x^2) + bx + c = 0 

Print roots specifying their nature. If roots are imaginary, no need to print the roots.

Print the nature of roots in the form of an integer -
 0 : if roots are real & same
 1 : if roots are real & different
-1 : if roots are imaginary
Round off the roots and then print the integral part only i.e. without any decimal places.
You can assume that, input will always be a quadratic equation.
Input format :
a b c (separated by space)
Output format :
Line 1 : Nature of roots (0 or 1 or -1)
Line 2 : Root 1 and Root 2 (separated by space)
Sample Input 1 :
1 4 2
Sample Output 1 :
1
-1 -3
Sample Input 2 :
1 2 3
Sample Output 2 :

-1
  1. import java.util.Scanner;
  2. public class Main
  3. {
  4. public static void main(String[] args) 
  5. {
  6. Scanner s = new Scanner (System.in);
  7. // System.out.println("enter the values a,b and c");
  8. int a = s.nextInt();
  9. int b = s.nextInt();
  10. int c = s.nextInt();
  11. double r1=0;
  12. double r2=0;
  13. int temp = b*b-4*a*c;
  14. r1 = (-b + Math.sqrt(temp)) / (2 * a);
  15. r2 = (-b - Math.sqrt(temp)) / (2 * a);
  16. if (temp<0)
  17. {
  18. System.out.println(-1);
  19. }
  20. else if(temp>0)
  21. {
  22. System.out.println(1);
  23. }
  24. else
  25. {
  26. System.out.println(0);
  27. }

  28. System.out.println();
  29. System.out.print(Math.round (r1)+" ");
  30. System.out.print(Math.round(r2));

  31. }
  32. }

No comments:

Post a Comment