Advertisement
Guest User

Untitled

a guest
Feb 27th, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. /***
  2. * Home assignment 01.
  3. */
  4. public class Task01 {
  5. /**
  6. * Function that solves an quadratic equation (a*x^2 + b*x + c = 0).
  7. * @param a A squared variable held constant (a*x^2).
  8. * @param b A variable held constant (b*x).
  9. * @param c An absolute term (c).
  10. * @return If equation has 2 roots (x1 and x2), returns the product of them (x1 * x2);
  11. * If equation has 1 root (x), returns it (x);
  12. * If equation has no roots, returns Double.NaN.
  13. */
  14. public static double solveQuadraticEquation(double a, double b, double c) {
  15.  
  16. //Calculate the discriminant and initialize d variable.
  17. double d = b*b-4*a*c ;
  18. double g = Math.sqrt(d);
  19.  
  20.  
  21.  
  22.  
  23. if (d > 0.0) {
  24. //Calculate the roots and initialize x1 and x2.
  25. double x1 = (-b + g)/2*a, x2 = (-b - g)/2*a;
  26.  
  27. //TODO: add your code here.
  28.  
  29. return x1 * x2;
  30. } else if (d == 0.0) {
  31. //Calculate the root and initialize x.
  32. double x = -b/2*a;
  33.  
  34. //TODO: add your code here.
  35.  
  36. return x;
  37. } else {
  38. //Initialize variable x with Double.NaN.
  39. double x = Double.NaN;
  40.  
  41. //TODO: add your code here.
  42.  
  43. return x;
  44. }
  45. }
  46.  
  47. /**
  48. * Entry-point of the program.
  49. * This is here so you can test out your code
  50. * with running this program.
  51. * @param args Arguments from command-line.
  52. */
  53. public static void main(String[] args) {
  54. System.out.println("a = 1, b = -5, c = 6: "
  55. + solveQuadraticEquation(1.0, -5.0, 6.0));
  56. // should be 6
  57. // add some more tests here if needed.
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement