Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***
- * Home assignment 01.
- */
- public class Task01 {
- /**
- * Function that solves an quadratic equation (a*x^2 + b*x + c = 0).
- * @param a A squared variable held constant (a*x^2).
- * @param b A variable held constant (b*x).
- * @param c An absolute term (c).
- * @return If equation has 2 roots (x1 and x2), returns the product of them (x1 * x2);
- * If equation has 1 root (x), returns it (x);
- * If equation has no roots, returns Double.NaN.
- */
- public static double solveQuadraticEquation(double a, double b, double c) {
- //Calculate the discriminant and initialize d variable.
- double d = b*b-4*a*c ;
- double g = Math.sqrt(d);
- if (d > 0.0) {
- //Calculate the roots and initialize x1 and x2.
- double x1 = (-b + g)/2*a, x2 = (-b - g)/2*a;
- //TODO: add your code here.
- return x1 * x2;
- } else if (d == 0.0) {
- //Calculate the root and initialize x.
- double x = -b/2*a;
- //TODO: add your code here.
- return x;
- } else {
- //Initialize variable x with Double.NaN.
- double x = Double.NaN;
- //TODO: add your code here.
- return x;
- }
- }
- /**
- * Entry-point of the program.
- * This is here so you can test out your code
- * with running this program.
- * @param args Arguments from command-line.
- */
- public static void main(String[] args) {
- System.out.println("a = 1, b = -5, c = 6: "
- + solveQuadraticEquation(1.0, -5.0, 6.0));
- // should be 6
- // add some more tests here if needed.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement