package lab 2; /** * @author wahl * A simple class for quadratic expressions of the form a*x^2 + b*x + c * (source code for lab 2, Algorithms, CS 225) * */ public class Quadratic { // data fields private double a; // coefficient of x^2 private double b; // coefficient of x private double c; // constant term /** * 3-arg constructor * Constructs the Quadratic object corresponding to a*x^2 + b*x + c * @param a (double) -- the leading coefficient * @param b (double) -- the middle coefficient * @param c (double) -- the constant term */ public Quadratic(double a, double b, double c) { // write 3 lines of code to implement } /** * converts this Quadratic to its String representation */ public String toString() { return a + "x^2 + " + b + "x + " + c; } /** * determines if this Quadratic has any real roots * @return true iff there are real roots */ public boolean hasRoots() { // a quadratic expression has real roots iff // b*b - 4*a*c is non-negative // write one or two lines of code to implement } /** * finds the real roots of this Quadratic object * @return an array of doubles r[0..1] containing the real roots * of this Quadratic function. If there are no real roots, both * entries in the returned array will have the value Float.Nan * ("not a number") */ public double[] roots() { // write code to declare & create array r // write code to calculate and store d = b*b - 4*a*c if(d < 0) // no real roots { r[0] = Float.NaN; // Float.NaN is a constant holding r[1] = Float.NaN; // a “Not-a-Number” value } else { // sq = square root of discriminant double sq = Math.sqrt(d); // write code to store root #1 in r[0] // write code to store root #2 in r[1] } // write a return statement to finish this method } // USE THE SOURCE MENU IN ECLIPSE TO AUTOMATICALLY GENERATE // GETTERS AND SETTERS /** * @return the a */ public double getA() { return a; } /** * @param a the a to set */ public void setA(double a) { this.a = a; } /** * @return the b */ public double getB() { return b; } /** * @param b the b to set */ public void setB(double b) { this.b = b; } /** * @return the c */ public double getC() { return c; } /** * @param c the c to set */ public void setC(double c) { this.c = c; } /** * main test method */ public static void main(String[] args) { // Create f(x) = x^2 - 5 Quadratic f = // Create g(x) = 0.005*x^2 + 10.8*x + 5.2 Quadratic g // Test the toString method System.out.println("f = " + f.toString()); System.out.println("g = " + g.toString()); // Find the roots of f and g double[] rootsF = double[] rootsG = // Report the roots of f and g System.out.print("The real roots of " + f.toString() + " are "); { if(!f.hasRoots()) System.out.print("nonexistent\n"); else System.out.println(rootsF[0] + " and " + rootsF[1]); } System.out.print("The real roots of " + g.toString() + " are "); { if(!g.hasRoots()) System.out.print("nonexistent\n"); else System.out.println(rootsG[0] + " and " + rootsG[1]); } } // end main } // end Quadratic 3