CS173: Intro to Computer Science - Functions (3 Points)
Developed by Professor Tralie and Professor Mongan.
Exercise Goals
The goals of this exercise are:- To write mathematical expressions in Java
- To write a function that computes an expression and returns its result
- To call a function from
main()
and use its return value
b*b
using the Math.pow()
method. The Math.sqrt()
method takes a double
parameter, which is the number whose root should be computed, and returns the result as a double
. Now write a program that calls a method that you will write to compute the quadratic root, and then have main()
print the root that you calculate.
Enter your Ursinus netid before clicking run. This is not your ID number or your email. For example, my netid is wmongan
(non Ursinus students can simply enter their name to get this to run, but they won't get an e-mail record or any form of credit).
Netid |
Driver.java
public class Driver {
public static double quadraticRoots(int a, int b, int c) {
// TODO write this function and return the result.
// There are two roots (-b "+ or -" ...)
// ... just compute -b + ...
}
public static void main(String[] args) {
// Solving for a root of x in x^2 - x - 6
double result = quadraticRoots(1, -1, -6);
System.out.println(result);
}
}
Driver.main(null);
Output
Quadratic Formula
For reference, the quadratic formula is:
\[\frac{-b \pm \sqrt{(b^{2} - 4ac)}}{2a}\]
given an equation:
\[ax^{2} + bx + c = 0\]
In this exercise, you can simply compute one of the roots, as follows:
\[\frac{-b + \sqrt{(b^{2} - 4ac)}}{2a}\]