Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.

Similar presentations


Presentation on theme: "Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left."— Presentation transcript:

1 Chapter 6 Mathematical Operations

2 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left side of the assignment operator ( = ) must be a variable All operations must be explicitly specified There is only one way to specify multiplication in C++ ( * )

3 6.1 Mathematical Expressions l-value - refers to what can be placed on the left of the assignment operator Constants and literals cannot be a l-value r-value - refers to what can be placed on the right of the assignment operator

4 6.1 Mathematical Expressions Binary operator - has two operands Unary operator - has one operand Widening conversion - any value can automatically be stored in a variable with a large enough data type

5 6.1 Mathematical Expressions Do not store a floating point number (decimal) in an integer They have two different memory representations Rule of thumb - match the l-value with the r- value

6 6.2 Assignment Operator ( = ) Replaces value on the left with the value on the right Value in var_a is replaced with a zero var_a = 0; All three variables’ values will be replaced with a 1 - Stylistically, avoid this type of statement var_a = var_b = var_c = 1; Value in var_a is replaced with the value in var_b var_a = var_b;

7 6.3 Standard Arithmetic Op’s ( +, -, *, /, % ) Mathematical operators available in C++ OperatorTypeDescriptionExample + BinaryAddition a = b + 5; – BinarySubtraction a = b – 5; – Unary Negation (changes sign of value) a = –b; * BinaryMultiplication a = b * 5; / BinaryDivision a = b / 5; % Binary Modulus (remainder of dividing right operand into left operand) a = b % 5;

8 Both operands of the modulus operator ( % ) must be integers Modulus operator often causes confusion in beginning programmers Following results in value of 2 being stored in var_a var_a = 5 % 3; 6.3 Standard Arithmetic Op’s (+, -, *, /, %)

9 When doing division pay attention to the data types of the operands Examples: x = 5 / 9; x = 5.0 / 9.0; x = 5.0F / 9.0F; First example - performs integer division resulting in a zero being stored in x

10 6.3 Standard Arithmetic Op’s ( +, -, *, /, % ) Examples: x = 5 / 9; x = 5.0 / 9.0; x = 5.0F / 9.0F; Second example does floating point division resulting in a double Example three does floating point division resulting in a float

11 6.4 Increment and Decrement Op’s ( ++,-- ) The increment ( ++ ) and decrement ( -- ) operators are unary operators Add one to the operand and subtract one from the operand Can be expanded as shown below ++int_exp; // pre-increment operator int_exp = int_exp + 1;

12 6.4 Increment and Decrement Op’s ( ++,-- ) Can be placed before or after the operand int int_exp = 0; ++int_exp; // Pre-increment operator cout << int_exp << endl; // Displays a 1 int_exp++; // Post-increment operator cout << int_exp << endl; // Displays a 2 Pre- and post-increment and decrement operators: No differences as standalone statements

13 6.4 Increment and Decrement Op’s ( ++,-- ) When embedded, pre- and post-increment and decrement operators behave differently int int_exp = 0; cout << ++int_exp << endl; // Displays a 1 cout << int_exp++ << endl; // Displays a 1 cout << int_exp << endl; // Displays a 2 Pre-operators change the value of the operand first and that value is used Post-operators use the value first and then change it

14 6.5 Compound Assign. Op’s (+=, –=, *=, /=, %=) Provide a shorthand notation for manipulating the value stored in a variable Following statement is common a = a + 2; Written using compound assignment operators a += 2;

15 6.5 Compound Assign. Op’s ( +=, –=, *=, /=, %= ) OperatorStatementExpansion +=a += 5;a = a + 5; -=a -= b;a = a – b; *=a *= b +.1;a = a * (b +.1); /=a /= b + c;a = a / (b + c); %=a %= 2;a = a % 2; Notice the expansions of the subtraction and division compound assignment operators require parentheses to achieve the same result

16 6.6 Accumulators Versus Counters Counter - a variable that is incremented Accumulator - a variable that has a value other than one added to itself Examples: “Count the number of people in a classroom.” - use a counter “What is a student’s accumulated loan debt?” - use an accumulator

17 6.6 Accumulators Versus Counters Always initialize counters and accumulators to a known value – usually zero int number_students = 0, student_loan = 0; // Counter number_students = number_students + 1; // or number_students++; // Accumulator student_loan = student_loan + 5000; // or student_loan += 5000;

18 6.7 Order of Precedence Order of precedence - established order that must be adhered to when evaluating expressions with multiple operations The table lists the operators starting with those that will be evaluated first postfix ++, postfix -- prefix ++, prefix --, unary - *, /, % +, - =, *=, /=, %=, +=, -=

19 6.7 Order of Precedence Parentheses used to change which operations are performed first Too many parentheses clutter up an expression - better to break up complicated expressions // Cluttered root = ((-b + sqrt( (b * b) - (4 * a * c)) ) / (2 * a)); // Not cluttered discriminant = b * b - 4 * a * c; denominator = 2 * a; root = (-b + sqrt( discriminant ) ) / denominator;

20 6.8 Mathematical Functions Function - refers to a task or job Function of a waiter is to serve food In programming, a function is a group of related statements that perform a specific task or job Parameter - value passed, or given to a function - sometimes called an argument

21 6.8 Mathematical Functions Some mathematical operations, such as exponentiation, do not have associated operators Provided as functions in an external header file called When included in an expression, a function is evaluated with the highest level of precedence (i.e., first)

22 6.8.1 The pow Function Exponentiations - accomplished by using the pow function, the syntax of which is shown below = pow(, ); The above syntax equates to the following mathematical expression lvalue = base power

23 6.8.1 The pow Function Base parameter can be any numeric data type except an int Power parameter can be any numeric data type Some compilers do support having an int for the base (those that are less compliant with the current standard)

24 6.8.1 The pow Function #include using std::cout; using std::endl; #include // Needed for pow int main() { const float PI = 3.141592F; float radius = 5; double area = 0; area = PI * pow( radius, 2 ); cout << area << " sq. in." << endl; return 0; }

25 6.8.1 The pow Function The functions in do not require the use of namespace statements Calling or executing a function has a certain amount of cost involved Multiplying the value by itself is more efficient than calling the pow function

26 6.8.2 The sqrt Function The sqrt function finds the square root of its parameter - syntax shown below = sqrt( ); Expects a floating point value for its parameter and returns a floating point value Type cast when the square root of integers is required

27 6.8.2 The sqrt Function An error results if the parameter is a negative number double value = 5; double square_root = 0; square_root = sqrt( value ); cout << "Square root: " << square_root << endl;

28 6.8.3 The abs function Returns absolute value of the parameter passed = abs( ); double value = -5; double square_root = 0; // Notice the nested function square_root = sqrt( abs( value ) ); cout << "Square root: " << square_root << endl;

29 6.8.3 The abs Function Some additional mathematical functions FunctionDescription sinReturns a floating point value which is the sine of the floating point parameter cos Returns a floating point value which is the cosine of the floating point parameter tan Returns a floating point value which is the tangent of the floating point parameter asin Returns a floating point value which is the arcsine of the floating point parameter log Returns a floating point value which is the natural log of the floating point parameter ceilReturns smallest integer greater than or equal to the floating point parameter floorReturns largest integer less than or equal to the floating point parameter

30 6.9 Type Casting Type casting - explicitly converting a value from one type to another Converting the return value of pow from a double to an integer double base = 5; int squared = 0; squared = static_cast ( pow( base, 2 )); cout << "Squared: " << squared << endl;

31 6.9 Type casting Notice the conversion of the variable val from an integer to a character, the character represented by the ASCII value float score = 0; double rvalue = 71.5; char grade = '\0'; int val = 67; score = static_cast ( rvalue ); grade = static_cast ( val ); cout << "Score: " << score << '\n' << "Grade: " << grade << endl;

32 6.9 Type Casting Other forms of type casting that, while common, should be avoided (unless writing a C program) score = (float)rvalue; score = float(rvalue);

33 6.11 C – The Differences Use instead of The pow and sqrt functions always are passed a double and return a double

34 6.11 C – The Differences FunctionData Type absint fabsdouble labslong Absolute values are calculated by the use of three different functions depending upon the data type of the parameter

35 6.11 C – The Differences Type casting uses one of the alternate styles previously discussed double y = 5.0; float x = static_cast ( y ); // C++ type casting float x = (float)y; // C type casting


Download ppt "Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left."

Similar presentations


Ads by Google