advertisement

Java Arithmetic First understand integer division (assumed by Java) some examples of integer division 10/2 10/3 10/4 4/10 5 3 2 0 now double division 10.0/2 10.0/3 10/4.0 10.0/5.0 5.0 3.333333 2.5 2.0 Casting To change one data type to another put the new type in parenthesis in front of the type you want to change, as follows: int n = 6; (double)n turns n into 6.0 10/4 evaluates to 2 because of integer division but (double)10/4 evaluates to 2.5 10/(double) also evaluates to 2.5 BUT BE CAREFUL OF ORDER OF OPERATIONS Casting comes before all operations EXCEPT () (double)(10/4) evaluates to 2.0 int x,y; (double)(x/y) will not do the same as (double)x/y or x/(double)y When you cast to an int you lose precision by truncating: (int) 10.7 / 5 2 What is modulus? You learned about the remainder long ago. 10 divided by 7 equals 1 with a remainder of 3 or 7 goes into 10, 1 time with 3 left over examples of modulus 10 % 2 10 % 3 10 % 4 4 % 10 0 % 10 10 % 0 0 1 2 4 0 error int x,y consider x % y if (x < y) x%y=x what are all the possible remainders for n % 5? (0,1,2,3,4) what are all possible remainders for a%b (0, 1, …. b -1) ASSIGNMENT PART 1: PRACTICE BY SOLVING Assume int x = 8; int y = 5; int a = 10; int b = 3; 12 / 7 100 / 30 3/9 0/5 1/2 -4/8 100/6.0 30.0/12 x/b y/x a/b (double)a / b y / (double) b b/(double)a (double)(y/x) (double)(10/7) 100 % 12 4 % 12 10 % 10 15 % 30 30 % 15 0%7 x%y a%x b%a a%b 0%y 1%b y%0 a%a What are all possible results for n % 7? ASSIGNMENT PART 2: Use for loops and the methods of the Math class from the AP Quick Reference Guide, to reproduce this table. Recall that System.out.print() prints without advancing to next line. N 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 101 106 111 116 121 126 N Squared 1 36 121 256 441 676 961 1296 1681 2116 2601 3136 3721 4356 5041 5776 6561 7396 8281 9216 10201 11236 12321 13456 14641 15876 Square Root of N 1 2.449489743 3.31662479 4 4.582575695 5.099019514 5.567764363 6 6.403124237 6.782329983 7.141428429 7.483314774 7.810249676 8.124038405 8.426149773 8.717797887 9 9.273618495 9.539392014 9.797958971 10.04987562 10.29563014 10.53565375 10.77032961 11 11.22497216 N Cubed 1 216 1331 4096 9261 17576 29791 46656 68921 97336 132651 175616 226981 287496 357911 438976 531441 636056 753571 884736 1030301 1191016 1367631 1560896 1771561 2000376 N to the 1/3 1 1.817120593 2.223980091 2.5198421 2.758924176 2.962496068 3.141380652 3.301927249 3.44821724 3.583047871 3.708429769 3.825862366 3.936497183 4.041240021 4.140817749 4.235823584 4.326748711 4.414004962 4.497941445 4.57885697 4.657009508 4.732623491 4.805895534 4.876998961 4.946087443 5.013297935 ASSIGNMENT PART 3: Write a method for 2-D Distance Formula – make it static so you can have it in the same class as a main method for easy testing. Given the two points (x1, y1) and (x2, y2), the distance between these points is given by the formula: