Saturday, October 22, 2016

// // Leave a Comment

Exercise 3.1 - Algebra: Solve Quadratic Equations

The program below is the answer to Liang's Introduction to Java Programming (9th Edition) Chapter 3 Exercise 3.1.
Liang Introduction to Java Exercise 3.1

/**
 *
 * @Author: Aghatise Osazuwa
 * Website: www.cscprogrammingtutorials.com
 * Exercise 3.1 - Algebra: Solve Quadratic Equations
 */

public class CheckerboardPatternOfAsterisks {
    public static void main (String [] args) {
        
        // declare variables
        double a, b, c, disc, r1, r2;
        
        // create Scanner to read user input
        Scanner input = new Scanner(System.in);

        // prompt user to enter details
        System.out.print("Enter a, b, c: ");
        a = input.nextDouble();
        b = input.nextDouble();
        c = input.nextDouble();

        //calculate the discriminant
        disc = b * b - (4 * a * c);
        
        //calculate the roots
        r1 = (-b + Math.pow(disc, 0.5)) / (2 * a);
        r2 = (-b - Math.pow(disc, 0.5)) / (2 * a);

        // display the results
        if (disc > 0){
                System.out.println("The roots are " + r1 + " and " + r2 + "\n");
        }
        
        if (disc == 0){
                System.out.println("The root is " + r1 + "\n");
        }
        
        if (disc < 0){
                System.out.println("The equation has no real roots.\n");
        }
    }
}
Solution to exercise 3.1
Sample Program run
Click here to see other solutions to Introduction to Java Programming.

0 comments:

Post a Comment


DISCLAIMER: Opinions expressed in comments are those of the comment writers alone and does not reflect or represent the views of the post author. We reserve the right to delete any post deemed inappropriate or offensive and/or spammy. Please do not use abusive words/hate speech.

I Appreciate your valuable Feedback. So, Please DO NOT SPAM - Spam comments will be deleted immediately.

Don't use brand name in name field and you're not allowed to use links in comments unless it's necessary. Such comments will be removed immediately.

Thanks.