|
|
|
|
|
int a = 3;
double b = 5.0, c;
c = a + b; // a (int) is converted to a double
// Then the addition is performed (on 2 doubles)
|
int a = 5, b = 2;
double c = 5.0, d;
d = c + a / b; // a/b is performed first.
// Because a and b are integers, the division
// a/b produces the quotient: a/b = 2 (not 2.5 !!!)
//
// Next we add: c + 2
// Because c is a double, the integer value 2
// is converted to double 2.0
// Result: 5.0 + 2.0 = 7.0
d = a + c / b; // c/b is performed first.
// Because c is doube and Java will convert
// b to double, and the division
// c/b produces the quotient: c/b = 2.5 !
//
// Next we add: a + 2.5
//
// Result: 5.0 + 2.5 = 7.5
|
public class Exercise2
{
public static void main(String[] args)
{
short a = 5;
int b = 2;
double c = 1.0;
double d = 5.0;
System.out.println( a / b / c );
System.out.println( a / c / b );
System.out.println( a / b );
System.out.println( d / b );
System.out.println( (a + 0) / b );
System.out.println( (d + 0) / b );
System.out.println( (a + 0.0) / b );
System.out.println( (d + 0.0) / b );
}
}
|
Answers:
a / b / c = 2.0 (double) a / c / b = 2.5 (double) a / b = 2 (int) d / b = 2.5 (double) (a + 0) / b = 2 (int) (d + 0) / b = 2.5 (double) (a + 0.0) / b = 2.5 (double) (d + 0.0) / b = 2.5 (double) |
How to run the program:
|