230 likes | 390 Views
APS105. Calculating. Basic Math Operations. 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 [ ].
E N D
APS105 Calculating
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 [ ]
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)
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 .
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
Assignment • 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;
Operation-Assignment • Some operations can be combined with ‘=‘ • Ie., +=, -=, *=, /=, %= • Examples: x += 2; x += 2 * y;
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
Common <math.h> Functions • Note: all arguments/return-values are doubles (absolute value)
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 <stdlib.h> • rand() returns an integer within 0..RAND_MAX
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
Mixing Types • If multiple types are used in an expression • the wider (more accurate) type is “contagious” • Example1: 2 + 5.3 .
Mixing Types: Example2 8 / 3 + 1.0 //
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) 5.7 + 8.9; int x = (int) (5.7 + 8.9);
More Cast Examples int x = (3 / 4) * 8; //