Java Reference
In-Depth Information
double half = 0.0;
if(x != 0)
{
half = x / 2.0;
System.out.println(x + “/2 = “ + half);
}
if(x == 0)
{
System.out.println(“The value of x is 0”);
}
int y = x * 5;
char grade = 'F';
if(y >= 85)
{
grade = 'A';
}
if(y >= 70 && y < 85)
grade = 'C';
System.out.println(“y = “ + y + “ and grade = “ + grade);
}
}
In the IfDemo program, I wanted to divide an int in half. If I had used the
statement x/2, the 2 would be treated as an int because 2 is an integer
literal. This would have given me an int as a result, meaning that any
remainder would have been lost. For example, 19/2 would result in 9,
not 9.5.
By using the statement “x/2.0,” I forced the x to be promoted to a double
before the division was calculated, thereby not losing any remainder. For
example, 19/2.0 results in 9.5, which is what I wanted in this particular
situation.
Figure 3.1
Sample outputs of the IfDemo program.
Search WWH ::




Custom Search