Basic trigonometry in Java Baeldung
I have been struggling with this issue for several days, so after a lot of searching, I decided to ask here.
Anyway, I need to use the method Math.tan()
, but it doesn't really work the way I want. Become if I set up a double variable: double i = opposite/adjacent
and then use a method Math.tan()
that just returns 0.0! For example:
double i = 480/640;
System.out.println(Math.tan(i));
But it still returns zero! I read that the method Math.tan()
returns "Radian". But because of this, it shouldn't return zero? Or I'm wrong? I know that if I use a real calculator and do tan (480/640) it will return what I want.
So I hope someone understands me and wants to help me! Thank you in advance! (By the way, sorry for the bad english)
source to share
In the calculations int
480/640
there is 0
. So the result i
will be 0.0
.
You need to write double i = 480.0/640;
(at least one of the numbers should be written as double
).
You can also write: double a = 480, b = 640;
and then if you write double i = a/b;
, you get a good result.
source to share
When you do math without casting, Java will implicitly make integers of literals - in your case, this will indeed result in 0.
Pass in the values before doing the math and you should be fine:
double i = 480D/640D;
System.out.println(i);
or
double i = (double)480/(double)640;
System.out.println(i);
or
double numerator = 480;
double denominator = 640;
double i = numerator / denominator;
System.out.println(i);
source to share