8-0-extra-arithmetic..

advertisement
8-0 extra
Things that have come up about
arithmetic
operators
Have a precedence:
* and /
are done before
+ and –
So, 3+4*5 is 23 not 35
If you want to make it 35 then use brackets
(3+4)*5
casting
VAT – what I said yesterday had a problem
I said:
int vat= price*.20;
Problem –right side is a double – the left an int
Instead
int vat = (int) price*.20;
This is called casting
Means you recognise you may lose information
Generally, some more arithmetic
If you take two ints and divide
23/12 it will equal the int result (1)
23 % 12 will equal 11 (the remainder)
So, the other version of VAT I gave you also has a problem:
int vat=price*VAT/100;
All the things are ints so you’ll lose some information
To get double results include a double
If you take say 5/2 the result will be 2
If you take 5/2.0 the result will be 2.5
So, int result=5/2;
//result 2
double result = 5/2.0;
//result 2.5
int result = 5/2.0;
//won’t compile
int result= (int) 5/2.0;
//result 2
What does all this mean for (your)
VAT calculation?
• Several possibilities, pick one and discuss
• Best might be to calculate everything as int pennies
and then print like this:
System.out.println
(“£”+pennies/100+”.”+ pennies%100);
Although that isn’t perfect (think about it)
or
Look up on internet how to print to 2 decimal places
Download