APS105 Calculating 1
Basic Math Operations 2
Basic Arithmetic Operators Operators: –Addition: + –Subtraction: - –Multiplication: * –Division: / Recall order of operations: –* and / have highest precedence –left to right otherwise Speficy grouping/precedence: ( ) –Not: { } or [ ] 3
Examples 4
The Modulo Operator % x % y returns the remainder of x / y has same precedence as / and * x and y must be ints –signs of x and y are ignored if either is negative –but result takes the sign of x (is negative if x is) 5
Modulo Examples. 6
Calculating with Char Values Recall ‘A’ is encoded in ASCII as decimal 65 char letter = ‘A’; // letter = 65 Since char value is a number can do math. 7
Increment and Decrement increment: ++ –adds one to the variable –AND changes the variable to this new value –i++; // means the same as i = i + 1; i = 10; i++; // i = 11 afterwards decrement: -- –subtracts one from the variable –AND changes the variable to this new value –i--; // means the same as i = i - 1; i = 10; i--; // i = 9 afterwards 8
Assignment 9
An assignment statement contains an ‘=‘ Evaluation order: –right-hand-side (RHS) of = is evaluated first –Then assignment of result to left-hand-side (LHS) Example: x = 5; x = x + 2; 10
Operation-Assignment Some operations can be combined with ‘=‘ –Ie., +=, -=, *=, /=, %= Examples: x += 2; x += 2 * y; 11
Library Functions 12
Library Functions Library functions: –Commonly-used functions –Packaged together as a “library” –Gain access to them by: Including the library in your program AND telling the compiler to link to the library Example: using the math library 13
Common Functions Note: all arguments/return-values are doubles (absolute value) 14
Random Numbers Generating truly random nums is hard! –Eg., gambling machine pattern discovered –Why? Most programs use “pseudo-random” nums –not perfectly random, close enough rand() function –in program (at top): #include – rand() returns an integer within 0..RAND_MAX 15
Example using rand() Generate a random int between 0 and 1 Generate a random int between 0 and 100 Generate a random int between 1 and 10 Generate a random even int bet. 2 and 10 16
Mixing Types and Casting 17
Mixing Types If multiple types are used in an expression –the wider (more accurate) type is “contagious” Example1:
Mixing Types: Example2 8 / // 19
Casting Casting lets you change one type into another –use casting to get the result type you want! int x = (int) 5.7; // Precedence of cast: –higher than * / –lower than
Cast Examples int x = (int) ; int x = (int) ( ); 21
More Cast Examples int x = (3 / 4) * 8; // 22