Java Reference
In-Depth Information
System.out.println("2 * 7 = " + (2 * 7));
System.out.println("5 / 2 = " + (5 / 2));
System.out.println("14 / 7 = " + (14 / 7));
System.out.println("34 % 5 = " + (34 % 5));
System.out.println("4 % 6 = " + (4 % 6));
}
}
Sample Run:
2 + 5 = 7
13 + 89 = 102
34 - 20 = 14
45 - 90 = -45
2 * 7 = 14
5 / 2 = 2
14 / 7 = 2
34 % 5 = 4
4 % 6 = 4
You should be careful when evaluating the mod operator with negative integer operands. You
might not get the answer you would expect. For example, -34 % 5 = -4 , because in the
division -34 / 5 , the quotient is -6 and the remainder is -4 . Similarly, 34 % -5 = 4 , because
in the division -34 / 5 , the quotient is -6 and the remainder is 4 .Also -34 % -5 = -4 ,
because in the division -34 / -5 , the quotient is 6 and the remainder is -4 .
EXAMPLE 2-3
The following Java program evaluates various floating-point expressions. (The details are
left as an exercise for you.)
// This program illustrates how floating-point expressions evaluate.
public class Example2_3
{
public static void main(String[] args)
{
System.out.println("5.0 + 3.5 = " + (5.0 + 3.5));
System.out.println("3.0 + 9.4 = " + (3.0 + 9.4));
System.out.println("16.4 - 5.2 = " + (16.4 - 5.2));
System.out.println("4.2 * 2.5 = " + (4.2 * 2.5));
System.out.println("5.0 / 2.0 = " + (5.0 / 2.0));
System.out.println("34.5 / 6.0 = " + (34.5 / 6.0));
System.out.println("34.5 % 6.0 = " + (34.5 % 6.0));
System.out.println("34.5 / 6.5 = " + (34.5 / 6.5));
System.out.println("34.5 % 6.5 = " + (34.5 % 6.5));
}
}
Search WWH ::




Custom Search