chapter 6 mathematical operations. 6.1 mathematical expressions in mathematics this expression is...
TRANSCRIPT
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++ ( * )
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
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
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.2 Assignment Operator ( = )Replaces value on the left with the value on
the right
Value in var_a is replaced with a zerovar_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_bvar_a = var_b;
6.3 Standard Arithmetic Op’s (+, -, *, /, %)
Mathematical operators available in C++
Operator Type Description Example
+ Binary Addition a = b + 5;
– Binary Subtraction a = b – 5;
– UnaryNegation (changes sign of value)
a = –b;
* Binary Multiplication a = b * 5;
/ Binary Division a = b / 5;
% BinaryModulus (remainder of dividing right operand into left operand)
a = b % 5;
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 (+, -, *, /, %)
6.3 Standard Arithmetic Op’s (+, -, *, /, %)
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
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
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 operatorint_exp = int_exp + 1;
6.4 Increment and Decrement Op’s (++,--)
Can be placed before or after the operandint int_exp = 0;
++int_exp; // Pre-increment operatorcout << int_exp << endl; // Displays a 1
int_exp++; // Post-increment operatorcout << int_exp << endl; // Displays a 2
Pre- and post-increment and decrement operators:
No differences as standalone statements
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 1cout << int_exp++ << endl; // Displays a 1cout << 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
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;
6.5 Compound Assign. Op’s (+=, –=, *=, /=, %=)
Operator Statement Expansion
+= 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
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
6.6 Accumulators Versus Counters
Always initialize counters and accumulators to a known value – usually zero
int number_students = 0, student_loan = 0;
// Counternumber_students = number_students + 1;// ornumber_students++;
// Accumulatorstudent_loan = student_loan + 5000;// orstudent_loan += 5000;
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 -
*, /, %
+, -
=, *=, /=, %=, +=, -=
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
// Clutteredroot = ((-b + sqrt( (b * b) - (4 * a * c)) ) / (2 * a));
// Not cluttereddiscriminant = b * b - 4 * a * c;denominator = 2 * a;
root = (-b + sqrt( discriminant ) ) / denominator;
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
6.8 Mathematical Functions
Some mathematical operations, such as exponentiation, do not have associated operators
• Provided as functions in an external header file called <cmath>
• When included in an expression, a function is evaluated with the highest level of precedence (i.e., first)
6.8.1 The pow Function
Exponentiations - accomplished by using the pow function, the syntax of which is shown below<l-value> = pow( <base>, <power> );
The above syntax equates to the following mathematical expressionlvalue = basepower
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)
6.8.1 The pow Function
#include <iostream>using std::cout;using std::endl;#include <cmath> // Needed for powint main(){ const float PI = 3.141592F; float radius = 5; double area = 0; area = PI * pow( radius, 2 ); cout << area << " sq. in." << endl; return 0;}
6.8.1 The pow Function
The functions in <cmath> 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
6.8.2 The sqrt Function
The sqrt function finds the square root of its parameter - syntax shown below
<float_point_l-value> = sqrt( <float_point_value>);
Expects a floating point value for its parameter and returns a floating point value
Type cast when the square root of integers is required
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;
6.8.3 The abs function
Returns absolute value of the parameter passed<numeric_l-value> = abs( <numeric_r-value> );
double value = -5;double square_root = 0;
// Notice the nested functionsquare_root = sqrt( abs( value ) );
cout << "Square root: " << square_root << endl;
6.8.3 The abs FunctionSome additional mathematical functions
Function Description
sin Returns a floating point value which is the sine of the floating point parameter
cosReturns a floating point value which is the cosine of the floating point parameter
tanReturns a floating point value which is the tangent of the floating point parameter
asinReturns a floating point value which is the arcsine of the floating point parameter
logReturns a floating point value which is the natural log of the floating point parameter
ceil Returns smallest integer greater than or equal to the floating point parameter
floor Returns largest integer less than or equal to the floating point parameter
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<int>( pow( base, 2 ));
cout << "Squared: " << squared << endl;
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<float>( rvalue );grade = static_cast<char>( val );
cout << "Score: " << score << '\n' << "Grade: " << grade << endl;
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);
6.11 C – The DifferencesUse <math.h> instead of <cmath>
The pow and sqrt functions always are passed a double and return a double
6.11 C – The Differences
Function Data Type
abs int
fabs double
labs long
Absolute values are calculated by the use of three different functions depending upon the data type of the parameter