I am new to Java. I want to print out the sin
, cos
and tan
values for every 15 degree interval.
public class W3Aufgabe5 {
public static void main(String[] args) {
System.out.printf("%6s%6s%6s%6s%n", "Angle", "Sin", "Cos", "Tan");
System.out.println("------------------------");
for (float angle = 0; angle <= 180; angle += 15) {
float sin = Math.sin(Math.toRadians(angle));
float cos = Math.cos(Math.toRadians(angle));
float tan = Math.tan(Math.toRadians(angle));
System.out.printf("%6d%6d%6d%6d%n", angle, sin, cos, tan);
}
}
}
For every Math.x()
line, the compiler prints
error: possible loss of precision
required: float
found: double
I don't really understand. Why does it require double
even though I am using float
all the time?
The trigonometric methods sin
, cos
, tan
, and toRadians
all accept double
as a parameter and return double
. There are no overloads that accept float
s and return float
s. It's legal to pass a float
to a method expecting a double
; it will be widened implicitly. But you can't narrow a double
to a float
implicitly when you assign the results to float
s.
You can explicitly cast the results to float
if you want, but you get better precision with double
, so declare your sin
, cos
, and tan
variables as double
s.
Also, the format specifier d
means integer values, not floating point values. Use the format specifier f
instead of d
. You may also want to place some spacing in between your values when you print them.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments