So today at school, we were learning some of the math classes in java, but I don't particularly understand this why it automatically rounds from -11.87 to -12.
import java.util.*;
public class println{
public static void main (String [] args){
System.out.println(8 % 3 / 15 - 12);
}
}
4 Answers 4
It does not "round up". The steps done here are pretty simple:
8%3is evaluated. the modulo operator%returns the rest of the integer-division 8/3 (so it returns 2)2 / 15is evaluated. Both2and15are integers (int) in java. Integer division will cut off any decimal places. So this expression will be evaluated to 0!0 - 12is evaluated. Result is-12
1 Comment
The reason for this is that all of the numbers you provided in the expression are in the form of non floating point numbers. Because of this, the JVM does not process the expressions with floating point numbers.
8 % 3 = 2
2 / 15 =わ 0
0 -ひく 12 =わ -ひく12
This is how the operation actually proceeds due to the fact that none of the numbers are floating point numbers (e.g. double).
5 Comments
Math.round()). It just cuts off the digits behind the decimal dot!In order to understand this, you should understand the structure of integer and double in Java. For example, if you code like that, it will not "round up".
public class println {
public static void main(String[] args) {
System.out.println(8.0 % 3.0 / 15.0 - 12.0);
}}
Because, the numbers, you used are integers (without any decimal). If you give the numbers in double form, the program gives you the exact result, which is -11.866666666666667.
2 Comments
double implicitly.Your expresion is ugual at this:
System.out.println(((8 % 3) / 15) - 12);
First evaluated
(8 % 3) = 2
And
(2/15) = 0
And finally
0-12 =-12