1. Member Join Date
Sep 2010
Posts
21
Rep Power
0

## Please explain how this bit of code works.

This is a code I wrote for Fundamental Java as an assignment. I wanted to round up the quotient of d and c and I found the answer on this website. But my question is how does the code that is colored red work? Thank you in advanced,

Allspark

//Allspark

public class Lab02_Ex2
{

final static int A = 7, B = 8;
final static double C = 4.23, D = 5.89;

public static void main(String [] args)
{
double dbl = D / C;
int x = (int)(dbl * 100.0); // Scale it
double dbl2 = ((double)x) / 100;

System.out.println( A + " + " + B + " = " + (A + B));
System.out.print( A + " * " + B + " = " + (A * B) + "\n");
System.out.println( B + " - " + A + " = " + (B - A));
System.out.println( D + " / " + C + " = " + dbl2);
System.exit(0);
}  Reply With Quote

2. ## double dbl = D / C; // divides D by C
int x = (int)(dbl * 100.0); // multiplies dbl by 100 and casts it to int (dropping fractional part
double dbl2 = ((double)x) / 100; // casts x to double and divides result by 100

If you print the value of dbl you'll see the results of the computations.  Reply With Quote

3. Member Join Date
Sep 2010
Posts
21
Rep Power
0

## By "dropping fractional part" you mean that it gets rid of everything after the decimal? For example D / C = 1.394, then you multiply by 100 and it becomes 139.4. but because it is cast into integer, it does not allow decimals therefore the solution is 139.0. then you divide by 100 to revert to the original scale. Did I understand this correctly?  Reply With Quote

4. ## Yes, you got it.  Reply With Quote

5. Member Join Date
Sep 2010
Posts
21
Rep Power
0

## Thanks Norm.  Reply With Quote

decimals, rounding up 