Download presentation
Presentation is loading. Please wait.
Published byGerard Harper Modified over 9 years ago
1
APS105 Calculating 1
2
Basic Math Operations 2
3
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
4
Examples 4
5
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
6
Modulo Examples. 6
7
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
8
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
9
Assignment 9
10
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
11
Operation-Assignment Some operations can be combined with ‘=‘ –Ie., +=, -=, *=, /=, %= Examples: x += 2; x += 2 * y; 11
12
Library Functions 12
13
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
14
Common Functions Note: all arguments/return-values are doubles (absolute value) 14
15
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
16
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
17
Mixing Types and Casting 17
18
Mixing Types If multiple types are used in an expression –the wider (more accurate) type is “contagious” Example1: 2 + 5.3. 18
19
Mixing Types: Example2 8 / 3 + 1.0 // 19
20
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 ++ -- 20
21
Cast Examples int x = (int) 5.7 + 8.9; int x = (int) (5.7 + 8.9); 21
22
More Cast Examples int x = (3 / 4) * 8; // 22
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.