Java Reference
In-Depth Information
As we noted in the previous section, the
Math
class has a method called
sqrt
that
computes the square root of a number. The method has the following header:
public static double sqrt(double n)
This header says that the method is called
sqrt
, that it takes a parameter of type
double
, and that it returns a value of type
double
.
Unfortunately, you can't just call this method directly by referring to it as
sqrt
because it is in another class. Whenever you want to refer to something declared in
another class, you use
dot notation:
<class name>.<element>
So you would refer to this method as
Math.sqrt
. Here's a sample program that
uses the method:
1
public class
WriteRoots {
2
public static void
main(String[] args) {
3
for
(
int
i = 1; i <= 20; i++) {
4
double
root = Math.sqrt(i);
5
System.out.println("sqrt(" + i + ") = " + root);
6
}
7
}
8 }
This program produces the following output:
sqrt(1) = 1.0
sqrt(2) = 1.4142135623730951
sqrt(3) = 1.7320508075688772
sqrt(4) = 2.0
sqrt(5) = 2.23606797749979
sqrt(6) = 2.449489742783178
sqrt(7) = 2.6457513110645907
sqrt(8) = 2.8284271247461903
sqrt(9) = 3.0
sqrt(10) = 3.1622776601683795
sqrt(11) = 3.3166247903554
sqrt(12) = 3.4641016151377544
sqrt(13) = 3.605551275463989
sqrt(14) = 3.7416573867739413
sqrt(15) = 3.872983346207417
sqrt(16) = 4.0
sqrt(17) = 4.123105625617661
sqrt(18) = 4.242640687119285
sqrt(19) = 4.358898943540674
sqrt(20) = 4.47213595499958
Search WWH ::
Custom Search