# Please explain how this bit of code works.

• 09-03-2010, 12:54 AM
Allspark
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);
}
• 09-03-2010, 01:10 AM
Norm
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.
• 09-03-2010, 01:19 AM
Allspark
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?
• 09-03-2010, 02:39 AM
Norm
Yes, you got it.
• 09-03-2010, 04:56 AM
Allspark
Thanks Norm.