6df35a986bd4846c8f6d90ef60b3b5e0.ppt
- Количество слайдов: 53
Operations and Expressions Chapter 3 C++ An Introduction to Computing, 3 rd ed.
Objectives Further work with Object-Centered Design Detailed look at numeric types Work with bool expressions Consider the processing of characters Study assignment operator Use increment, decrement operators First look at class constructors C++ An Introduction to Computing, 3 rd ed. 2
Problem Use Einstein's equation to calculate the amount of energy released by a quantity of mass given in the problem For energy released, enter mass General (Must be non-negative): 123 Energy released = 999. 99 units Behavior C++ An Introduction to Computing, 3 rd ed. 3
Objects Description Software Objects Type Kind Name screen ostream varying prompt string constant quantity of matter double varying mass istream varying cin qty of energy double varying energy descriptive label string constant keyboard C++ An Introduction to Computing, 3 rd ed. cout 4
Operations Display a string (the prompt) on the screen ii. Read a nonnegative number (mass) from the keyboard iii. Compute energy from mass iv. Display a number (energy) and a string on the screen i. C++ An Introduction to Computing, 3 rd ed. 5
Additional Elements We note that step iii. requires Einstein's equation This implies a few more operations v. Exponentiation vi. Multiplication of reals vii. Storage of a real And additional objects Description Speed of light 2 Software Objects Type Kind Name double constant SPEED_OF_LIGHT int constant C++ An Introduction to Computing, 3 rd ed. 6
Algorithm We organize the objects and operations into an algorithm: 1. Declare the constant SPEED_OF_LIGHT. 2. Display to cout a prompt for the mass to be converted into energy. 3. Read a nonnegative number from cin into mass. 4. Compute 5. Display to cout a descriptive label and energy. C++ An Introduction to Computing, 3 rd ed. 7
Coding, Execution, Testing Figure 3. 1 shows the source code Sample execution runs are also shown • Two runs with simple test data for easy checking • One run with more realistic data C++ An Introduction to Computing, 3 rd ed. 8
Expressions Definition: any sequence of objects and operations that combine to produce a value is called an expression. Example: double pressure = ((depth / FEET_PER_ATM) + 1) * LBS_PER_SQ_IN_PER_ATM; C++ An Introduction to Computing, 3 rd ed. 9
Numeric Expressions C++ provides four familiar arithmetic operators: • • + for performing addition - for performing subtraction * for performing multiplication / for performing division Each of these four can be applied to either real (double) or integer (int) operands. C++ An Introduction to Computing, 3 rd ed. 10
Division behaves differently for int and double operands • Note the results of the following 3/4 ® 0 3. 0/4. 0 ® 0. 75 3. 0/4 ® 0. 75 3/4. 0 ® 0. 75 If both operands are integers • Integer division performed • Otherwise real division performed C++ An Introduction to Computing, 3 rd ed. 11
Integer vs. Real Division Recall division from grade school. Teacher: “ 4 goes into 3 how many times? ” Pupils: “ 0 times with a remainder 4” The expression 3 / 4 returns the quotient. • This is integer division The expression 3 % 4 returns the remainder. • This is read, "3 mod 4" C++ An Introduction to Computing, 3 rd ed. 12
Type Conversions Combining an int and a real in the same expression • 2 + 3. 0 5. 0 C++ automatically converts narrow values into wider values • An integer is converted to a real • Result of the expression is a real Often called "promotion" C++ An Introduction to Computing, 3 rd ed. 13
Precedence Consider the possible value of the expression 2 + 3 * 4 (2 + 3) * 4® 24 or 2 + (3 * 4) ® 14 ? Operator precedence governs evaluation order. * has higher precedence than + * is applied first C++ An Introduction to Computing, 3 rd ed. 14
Operator Precedence () HIGHER + (positive), - (negative), ! (NOT) *, /, % <, <=, >, >= ==, != && LOWER || See Appendix C for a complete list. . . C++ An Introduction to Computing, 3 rd ed. 15
Associativity Consider the possible value of the expression 8 - 4 - 2 ® 4 8 - (4 - 2) ® 6 ? (8 - 4) - 2 or Precedence doesn’t help us Associativity tells us. • Subtraction is left-associative, the left - is evaluated first, giving us 4. Most (but not all) C++ operators associate left. • See Appendix C in the text for a complete list. . . C++ An Introduction to Computing, 3 rd ed. 16
Numeric Functions The library
Using
Type Conversions Possible to explicitly convert a value from one type to another Syntax to use: or (type) expression Conversion cause loss of data type (expression) double x = 3. 456; cout << (int) x; 3 What gets output? C++ An Introduction to Computing, 3 rd ed. 19
Boolean Expressions C++ type bool has two literals • false and true Relational operators produce boolean expressions C++ An Introduction to Computing, 3 rd ed. 20
Relational Operations Use operators for comparisons • Each takes two operands • Produces a bool value (true or false): x == y x != y x < y x >= y x > y x <= y Warning: • Do NOT confuse = (assignment) • With == (equality). C++ An Introduction to Computing, 3 rd ed. 21
Compound Boolean Expressions Logical operators C++ An Introduction to Computing, 3 rd ed. 22
Compound Boolean Expressions More complex boolean expressions can be built using the logical operators: a && b a || b !a // true iff a, b are both true // true iff a or b is true // true iff a is false Example: cin >> score; assert (0 <= score && score <= 100); C++ An Introduction to Computing, 3 rd ed. 23
Short-Circuit Evaluation Consider the boolean expression ( n != 0 ) && ( x < 1. 0 / n ) • If n == 0 the right hand expression causes a program crash C++ will evaluate the original expression from left to right • If n == 0, the left expression evaluates false • Since it is an &&, this makes the whole expression false • Thus it does not proceed to the right expression C++ An Introduction to Computing, 3 rd ed. 24
Preconditions Definition: When a program makes assumptions about its input values • Example: that they’re positive Preconditions are boolean expressions • Must be true in order for the program to work correctly. To check preconditions, C++ provides the assert() mechanism. . . C++ An Introduction to Computing, 3 rd ed. 25
Assertions Required to use the #include
Character Expressions Character variables can be … Declared and initialized • char middle. Initial = 'Q'; Assigned • middle. Initial = 'Z'; Used for I/O • cout << middle. Initial; • cin >> middle. Initial; Compared • assert (middle. Initial != 'X'); C++ An Introduction to Computing, 3 rd ed. 27
Character Functions Boolean character-processing functions found in
Assignment Syntax: variable = expression; • Expression is evaluated • Value placed in memory location associated with variable Example: x. Coord = 4. 56; code = 'T'; C++ An Introduction to Computing, 3 rd ed. 29
Assignment Given the sequence of three assignment statements, note the results Note that previous variable values are gone after execution of assignment 30 C++ An Introduction to Computing, 3 rd ed.
Assignment The assignment operator = • Right-associative, • Supports expressions like: int w, x, y, z; w = x = y = z = 0; The rightmost = is applied first, • • assigning z zero, then y is assigned the value of z (0), then x is assigned the value of y (0) finally w is assigned the value of x (0). C++ An Introduction to Computing, 3 rd ed. 31
Assignment Shortcuts Some assignments are so common: var = var + x; var = var - y; // add x to var // sub y from var C++ provides shortcuts for them: var += x; var -= y; // add x to var // sub y from var C++ An Introduction to Computing, 3 rd ed. 32
In General Most arithmetic expressions of the form: var = var D value; can be written in the “shortcut” form: var D= value; Examples: double x, y; cin >> x >> y; x *= 2. 0; // double x’s value y /= 2. 0; // decrease y by half C++ An Introduction to Computing, 3 rd ed. 33
Increment and Decrement Other common assignments include: var = var + 1; var = var - 1; // add 1 to var // sub 1 from var C++ provides shortcuts for them, too: var++; var--; // add 1 to var // sub 1 from var C++ An Introduction to Computing, 3 rd ed. 34
Prefix Increment The prefix form of increment produces the final (incremented) value as its result: int x, y = 0; x = ++y; cout << x; // 1 is displayed The prefix decrement behaves similarly. . . C++ An Introduction to Computing, 3 rd ed. 35
Postfix Increment The postfix form of increment produces the original (unincremented) value as its result: int x, y = 0; x = y++; cout << x; // 0 is displayed // y now holds value of 1 The prefix decrement behaves similarly. . . C++ An Introduction to Computing, 3 rd ed. 36
Prefix vs. Postfix So long as the increment (or decrement) operator is used as a separate statement: int y = 0, x = 0; ++x; // x == 1 y++; // y == 1 … it makes no difference which version is used. C++ An Introduction to Computing, 3 rd ed. 37
Expressions into Statements – Semicolons An expression followed by a semicolon becomes an expression statement • x = y + z; • 'A'; • cos (z); This expression statement has the added side All are expression effect of changing the value of x statements C++ An Introduction to Computing, 3 rd ed. 38
I/O Streams C++ has no I/O as part of the language • I/O streams are provided by istream and ostream cout cin C++ An Introduction to Computing, 3 rd ed. 39
Input Expressions Form • input_stream >> variable; May be chained together cin >> x >> y; Adapts to whatever type variable is • User must enter correct type Best to prompt user for input expected • cout << "Enter choice (1 – 10) : " C++ An Introduction to Computing, 3 rd ed. 40
Output Expressions Form • output_stream << expression; May be chained • cout << "The sum = " << sum; The expression can be a variable, a constant or a combination using operators • cout << "Sum = " << v 1 + v 2 + v 3; The expression adapts to whatever types are used C++ An Introduction to Computing, 3 rd ed. 41
Output Formatting Possible to specify appearance of output From iostream: • showpoint Display decimal point and trailing zeros for all real numbers. • noshowpoint Hide decimal point and trailing zeros for whole real numbers (default). Must specify the proper • fixed Use fixed-point notation for real values. include files to notation for • scientific Use scientific use these. real values. • boolalpha Display boolean values as strings “true” and “false”. #include
Objected-Centered Design Problem: A manufacturing company uses trucks for delivery. For each trip, the driver records mileage, gallons of fuel, cost of fuel, etc. The accountants want a report for miles per gallon, total trip cost, cost per mile. The controller wants a program to assist in recording and calculating these statistics C++ An Introduction to Computing, 3 rd ed. 43
Behavior For trip statistics: Enter miles traveled: 99 Enter gallons fuel: 99. 99 Enter cost per gallon : 99. 99 Enter per mile cost for this truck: 9. 99 Mileage for this trip : 99. 99 Total trip cost : 99. 99 Trip cost per mile: 99. 99 C++ An Introduction to Computing, 3 rd ed. 44
Objects Description screen Software Objects Type Kind Name ostream variable cout total miles traveled double variable miles total gallons used double variable gallons. Of. Fuel fuel cost per gallon double variable unit. Fuel. Cost operating cost/mi double variable unit. Operating. Cost istream variable cin miles per gallon double variable miles. Per. Gallon total cost of trip double variable total. Trip. Cost cost per mile double variable cost. Per. Mile keyboard C++ An Introduction to Computing, 3 rd ed. 45
Operations Display prompt on screen for input Read sequence of four reals from keyboard Compute mpg i. iii. • Compute total cost of trip: add. . iv. • • cost of fuel = gallons * price / gallon operating costs = miles * cost / mile Compute cost of trip per mile v. • vi. divide miles by number of gallons Divide total cost by number of miles traveled Output real values C++ An Introduction to Computing, 3 rd ed. 46
Algorithm 1. Display a prompt via cout for miles, gallons. Of. Fuel, unit. Fuel. Cost, and unit. Operating. Cost. 2. Read values from cin into miles, gallons. Of. Fuel, unit. Fuel. Cost, and unit. Operating. Cost. 3. Check that each of these values is positive. 4. Compute miles. Per. Gallon = miles / gallons. Of. Fuel. 5. Compute fuel. Cost = gallons. Of. Fuel * unit. Fuel. Cost. 6. Compute operating. Cost = unit. Operating. Cost * miles. 7. Compute total. Trip. Cost = fuel. Cost + operating. Cost. 8. Compute cost. Per. Mile = total. Trip. Cost / miles. 9. Via cout, display miles. Per. Gallon, total. Trip. Cost and cost. Per. Mile, with descriptive labels. C++ An Introduction to Computing, 3 rd ed. 47
Coding, Execution, Testing View source code Figure 3. 2 Note use of • prompting • input expressions • formatting of output View sample runs C++ An Introduction to Computing, 3 rd ed. 48
OBJECTive Thinking: Initializing and Constructors Constructor: special mechanism to initialize instance variables of a class object • Uses assignment statements • Can have default values or pass values to the constructor Constructor called when a class object is declared • Sphere big. Sphere, little. Sphere; C++ An Introduction to Computing, 3 rd ed. 49
A Sphere Constructor class Sphere Declaration of the { constructor public: Sphere(); . . . other Sphere-operation declarations go here private: double my. Radius, my. Density, my. Weight; Definition of the constructor }; inline Sphere: : Sphere() { my. Radius = my. Density = my. Weight = 0. 0; } C++ An Introduction to Computing, 3 rd ed. 50
A Sphere Constructor When Sphere object called: #include "Sphere. h" int main() { Sphere one. Sphere, another. Sphere; } Private variables of each are initialized C++ An Introduction to Computing, 3 rd ed. 51
A Name Constructor Possible to pass parameters to the constructor #include
A Name Constructor Now declaration can include specific initial values #include "Name. h" int main() { Name his. Name("John", "Paul", "Jones"), her. Name("Mary", "Anne", "Smith"), its. Name; } C++ An Introduction to Computing, 3 rd ed. 53