Download presentation
Presentation is loading. Please wait.
Published byLee Norris Modified over 9 years ago
2
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington
3
2 Chapter 3 Topics Constants of Type int and float l Evaluating Arithmetic Expressions l Implicit Type Coercion and Explicit Type Conversion l Calling a Value-Returning Function l Using Function Arguments l Using C++ Library Functions in Expressions l Calling a Void Function l C++ Manipulators to Format Output String Operations length, find, substr
4
3 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
5
4 C++ Simple Data Types simple types integralfloating char short int long bool enum float double long double unsigned
6
5 Standard Data Types in C++ l Integral Types n represent whole numbers and their negatives n declared as int, short, or long l Floating Types n represent real numbers with a decimal point n declared as float, or double l Character Type n represents single characters n declared as char
7
6 Samples of C++ Data Values int sample values 4578 -45780 float sample values 95.27495..265 9521E-3-95E-195.213E2 char sample values ‘ B ’ ‘ d ’ ‘ 4 ’‘ ? ’ ‘ * ’
8
7 Scientific Notation 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.00027
9
8 More About Floating Point Values l floating point numbers have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing EXAMPLES 18.4 500..8 -127.358 l alternatively, floating point values can have an exponent, as in scientific notation--the number preceding the letter E doesn’t need to include a decimal point EXAMPLES 1.84E1 5E2 8E-1 -.127358E3
10
9 Division Operator l the result of the division operator depends on the type of its operands l if one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type l Examples 11 / 4 has value 2 11.0 / 4.0 has value 2.75 11 / 4.0 has value 2.75
11
10 Modulus Operator l the modulus operator % can only be used with integer type operands and always has an integer type result l its result is the integer type remainder of an integer division EXAMPLE 11 % 4 has value 3 because ) 4 11 R = ?
12
Modulo Arithmetic (%) l % operator n yields remainder of integer division l 5 % 3 = 2 l 9 % 4 = 1 l 8 % 2 = 0 l 3 % 5 = 3
13
l 3 + 6 = ? l 9l 9 l 3.4 - 6.1 = ? l -2.7 l 2 * 3 = ? l 6l 6 l 8 / 2 = ? l 4l 4 l 8.0 / 2.0 = ? l 4.0 l 8 / 8 = ? l1l1
14
l 8 / 9 = ? l0l0 l 8 / 7 = ? l1l1 l 8 % 8 = ? l0l0 l 8 % 9 = ? l8l8 l 8 % 7 = ? l1l1 l 0 % 7 = ? l0l0
15
14 Increment / Decrement Operators
16
15 More C++ Operators 8 int age; age = 8; age = age + 1; age 9
17
16 PREFIX FORM Increment Operator 8 int age; age = 8; ++age; age 9
18
17 POSTFIX FORM Increment Operator 8 int age; age = 8; age++; age 9
19
18 Decrement Operator 100 int dogs; dogs = 100; dogs--; dogs 99 dogs
20
19 Which Form to Use l when the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form dogs-- ; --dogs ; USE EITHER
21
20 BUT... l when the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results WE’LL SEE HOW LATER...
22
21 Operators & Expressions
23
22 What is an Expression in C++? l An expression is a valid arrangement of variables, constants, and operators. l in C++ each expression can be evaluated to compute a value of a given type l the value of the expression 9.3 * 4.5 is 41.85
24
23 Operators can be binaryinvolving 2 operands 2 + 3 unaryinvolving 1 operand- 3 ternary involving 3 operands later
25
24 Some C++ Operators Precedence OperatorDescription Higher ( )Function call +Positive - Negative *Multiplication / Division % Modulus (remainder) +Addition - Subtraction Lower = Assignment
26
25 Precedence l higher Precedence determines which operator is applied first in an expression having several operators
27
26 Associativity l left to right Associativity means that in an expression having 2 operators with the same priority, the left operator is applied first l in C++ the binary operators *, /, %, +, - are all left associative l expression 9 - 5 - 1 means ( 9 - 5 ) - 1 4 - 1 3
28
27 7 * 10 - 5 % 3 * 4 + 9 means (7 * 10) - 5 % 3 * 4 + 9 70 - 5 % 3 * 4 + 9 70 - (5 % 3) * 4 + 9 70 - 2 * 4 + 9 70 - ( 2 * 4 ) + 9 70 - 8 + 9 ( 70 - 8 ) + 9 62 + 9 71 Evaluate the Expression
29
28 Parentheses l parentheses can be used to change the usual order l parts in ( ) are evaluated first evaluate (7 * (10 - 5) % 3) * 4 + 9 ( 7 * 5 % 3 ) * 4 + 9 ( 35 % 3 ) * 4 + 9 2 * 4 + 9 8 + 9 17
30
29 Assignment Operator
31
30 Variable = Expression l first, Expression on right is evaluated l then the resulting value is stored in the memory location of Variable on left NOTE: An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable Assignment Operator Syntax
32
31 Expression = Variable Do NOT put the expression on the left!! rate * time = distance;// major error Assignment Syntax NOT
33
32 What value is stored? float a; float b; a = 8.5; b = 9.37; a = b; a b a b 8.5 9.37 ? ?
34
33 What is stored? ? float someFloat; someFloat someFloat = 12; // causes implicit type conversion someFloat 12.0
35
34 What is stored? ? int someInt; someInt someInt = 4.8; // causes implicit type conversion someInt 4
36
35 Type Casting
37
36 Type Casting is Explicit Conversion of Type int(4.8) has value4 float(5)has value5.0 float(7/4)has value1.0 float(7) / float(4)has value1.75
38
37 Some Expressions int age; EXAMPLEVALUE age = 8 8 - age- 8 5 + 813 5 / 8 0 6.0 / 5.01.2 float ( 4 / 8 )0.0 float ( 4 ) / 80.5 cout << “How old are you?” cout cin >> agecin cout << agecout
39
38 What values are stored? float loCost; float hiCost; loCost = 12.342; hiCost = 12.348; loCost = float (int (loCost * 100.0 + 0.5) ) / 100.0; hiCost = float (int (hiCost * 100.0 + 0.5) ) / 100.0;
40
39 Values were rounded to 2 decimal places 12.34 hiCost 12.35 loCost
41
40 Function Concept in Math f ( x ) = 5 x - 3 When x = 1, f ( x ) = 2 is the returned value. When x = 4, f ( x ) = 17 is the returned value. Returned value is determined by the function definition and by the values of any parameters. Name of function Parameter of function Function definition
42
41 What is in a block? { 0 or more statements here }
43
42 Every C++ function has 2 parts int main ( ) heading { body block return 0; }
44
43 Shortest C++ Program int main ( ) { return 0; } type of returned value name of function
45
44 What is in a heading? int main ( ) type of returned value name of function says no parameters
46
45 Where are functions? located in libraries OR written by programmers
47
46 HEADER FILE FUNCTION EXAMPLE VALUE OF CALL fabs(x) fabs(-6.4) 6.4 pow(x,y) pow(2.0,3.0) 8.0 sqrt(x) sqrt(100.0) 10.0 setprecision(n) setprecision(3) log(x) n.log log(2.0).693147 sqrt(x) sqrt(2.0) 1.41421 abs(i) abs(-6) 6
48
47 Write C++ Expressions for The square root of b 2 - 4ac sqrt ( b * b - 4.0 * a * c ) The square root of the average of myAge and yourAge sqrt ( ( myAge + yourAge ) / 2 )
49
Two Kinds of Functions Always returns a single value to its caller and is called from within an expression. Never returns a value to its caller, and is called as a separate statement. Value-Returning Void
50
49 Output
51
50 << is a binary operator << is called the output or insertion operator << is left associative EXPRESSIONHAS VALUE cout << age cout STATEMENT cout << “You are “ << age << “ years old\n” ;
52
51 is header file l for a library that defines 3 objects an istream object named cin (keyboard) an ostream object named cout (screen) an ostream object named cerr (screen)
53
52 No I/O is built into C++ l instead, a library provides input stream and output stream KeyboardScreen executing program istreamostream
54
53 Insertion Operator ( << ) l the insertion operator << takes 2 operands l the left operand is a stream expression, such as cout l the right operand is an expression of simple type, or a string, or a manipulator
55
54 Output Statements SYNTAX (revised) cout << ExpressionOrManipulator << ExpressionOrManipulator... ;
56
55 Output Statements SYNTAX These examples yield the same output. cout << “The answer is “ ; cout << 3 * 4 ; cout << “The answer is “ << 3 * 4 ; cout << Expression << Expression... ;
57
l Examples: n int x; double y; char z; l x = 1; y = 2.3; z = ‘A’; l cout << "x ="; l cout << x << "y =" << y << "z =" << z; l cout << "***"; l Output: l x =1y =2.3z =A*** n Insert white spaces in the output where needed!
58
x = 1; y = 2.3; z = ‘A’; cout << "x = "; cout << x << " y = " << y << " z = " << z; cout << " ***"; Output: x = 1 y = 2.3 z = A ***
59
l x = 1; y = 2.3; z = ‘A’; l cout << "x = " << x << endl << "y = " << y l << endl << "z = " << z << endl; Output: x = 1 y = 2.3 z = A l x = -12345; y = 1.23456789; z = ‘B’; l cout << x << " " << y << " " << z; l Output: -12345 1.23457 B
60
59 I/O Manipulators
61
60 Manipulators l manipulators are used only in input and output statements l endl, fixed, showpoint, setw, and setprecision are manipulators that can be used to control output format l endl is use to terminate the current output line, and create blank lines in output
62
61 Using Manipulators Fixed and Showpoint l use the following statement to specify that (for output sent to the cout stream) decimal format (not scientific notation) be used, and that a decimal point be included (even for floating values with 0 as fractional part) l cout << fixed << showpoint;
63
62 setprecision(n) l requires #include and appears in an expression using insertion operator (<<) l if fixed has already been specified, argument n determines the number of places displayed after the decimal point for floating point values l remains in effect until explicitly changed by another call to setprecision
64
63 What is exact output? #include // for setw( ) and setprecision( ) #include using namespace std; int main ( ) { float myNumber = 123.4587 ; cout << fixed; // use decimal format cout << showpoint; // print decimal points cout << “Number is ” << setprecision ( 3 ) << myNumber << endl ; return 0 ; }
65
64 OUTPUT Number is 123.459 value is rounded if necessary to be displayed with exactly 3 places after the decimal point
66
65 Manipulator setw l “set width” lets us control how many character positions the next data item should occupy when it is output l setw is only for formatting numbers and strings, not char type data
67
66 setw(n) l requires #include and appears in an expression using insertion operator (<<) l argument n is called the fieldwidth specification, and determines the number of character positions in which to display a right-justified number or string (not char data). The number of positions used is expanded if n is too narrow l “set width” affects only the very next item displayed, and is useful to align columns of output
68
67 What is exact output? #include // for setw( ) #include using namespace std; int main ( ) { int myNumber = 123 ; int yourNumber = 5 ; cout << setw ( 10 ) << “Mine” << setw ( 10 ) << “Yours” << endl; << setw ( 10 ) << myNumber << setw ( 10 ) << yourNumber << endl ; return 0 ; }
69
68 OUTPUT 12345678901234567890 Mine Yours 123 5 each is displayed right-justified and each is located in a total of 10 positions position
70
69 What is exact output? #include // for setw( ) and setprecision( ) #include using namespace std; int main ( ) { float myNumber = 123.4 ; float yourNumber = 3.14159 ; cout << fixed; // use decimal format cout << showpoint; // print decimal points cout << “Numbers are: ” << setprecision ( 4 ) << endl << setw ( 10 ) << myNumber << endl << setw ( 10 ) << yourNumber << endl ; return 0 ; }
71
70 OUTPUT Numbers are: 123.4000 3.1416 each is displayed right-justified and rounded if necessary and each is located in a total of 10 positions with 4 places after the decimal point 12345678901234567890
72
71 float x = 312.0 ; float y = 4.827 ; cout << fixed; cout << showpoint; cout << setprecision ( 2 ) << setw ( 10 ) << x << endl ’’’’ 3 1 2.00 << setw ( 10 ) << y << endl ; ’’’’’’ 4.83 cout << setprecision ( 1 ) << setw ( 10 ) << x << endl ’’’’’ 3 1 2.0 << setw ( 10 ) << y << endl ; ’’’’’’’ 4.8 cout << setprecision ( 5 ) << setw ( 7 ) << x << endl 3 1 2.00000 << setw ( 7 ) << y << endl ; 4.82700 More Examples x 312.0 y 4.827
73
72 HEADER MANIPULATOR ARGUMENT EFFECT FILE TYPE showpoint none displays decimal point fixed none suppresses scientific notation setprecision(n) int sets precision to n digits setw(n) int sets fieldwidth to n positions endl none terminates output line
74
73 setw Manipulator cout << setw(5) << someInt; l controls # columns next data item occupies l for numbers, strings, not char l the # columns is called the FIELD l output right justified
75
74 setw Manipulator int ans = 33, num = 7132; cout << setw(4) << ans << setw(5) << num << setw(4) << "Hi";__33_7132__Hi 12 cout << setw(2) << ans << setw(4) << num << setw(2) << "Hi";337132Hi cout << setw(6) << ans << setw(3) << "Hi" << setw(5) << num;____33_Hi_7132 1234
76
75 setw Manipulator int ans = 33, num = 7132; cout << setw(7) << "Hi" << setw(4) << num;_____Hi7132 12345 cout << setw(1) << ans << setw(5) << num;33_7132 cout << "Hi" << setw(5) << ans << num;Hi___337132 123
77
76 setw With float Values float x = 4.85; cout << setw(4) << x << endl4.85 << setw(6) << x << endl 4.85 << setw(3) << x << endl;4.85 cout << 123456789.5;1.234567E+08 cout << 95.0; 95 l Fixes the last two problems: cout << fixed << showpoint;
78
77 String Functions
79
78 length Function function length returns an unsigned integer value that equals the number of characters currently in the string function size returns the same value as function length you must use dot notation in the call to function length or size
80
79 find Function function find returns an unsigned integer value that is the beginning position for the first occurrence of a particular substring within the string the substring argument can be a string constant, a string expression, or a char value if the substring was not found, function find returns the special value string::npos
81
80 substr Function function substr returns a particular substring of a string l the first argument is an unsigned integer that specifies a starting position within the string l the second argument is an unsigned integer that specifies the length of the desired substring l positions of characters within a string are numbered starting from 0, not from 1
82
81 What is exact output? #include #include // for functions length, find, substr using namespace std; int main ( ) { string stateName = “Mississippi” ; cout << stateName.length( ) << endl; cout << stateName.find(“is”) << endl; cout << stateName.substr( 0, 4 ) << endl; cout << stateName.substr( 4, 2 ) << endl; cout << stateName.substr( 9, 5 ) << endl; return 0 ; }
83
82 What is exact output? #include #include // for functions length, find, substr using namespace std; int main ( ) { string stateName = “Mississippi” ; cout << stateName.length( ) << endl; // value 11 cout << stateName.find(“is”) << endl;// value 1 cout << stateName.substr( 0, 4 ) << endl;// value “Miss” cout << stateName.substr( 4, 2 ) << endl;// value “is” cout << stateName.substr( 9, 5 ) << endl;// value “pi” return 0 ; }
84
83 Case Study
85
84 Map Measurement Case Study You want a program to determine walking distances between 4 sights in the city. Your city map legend says one inch on the map equals 1/4 mile in the city. You use the measured distances between 4 sights on the map. Display the walking distances (rounded to the nearest tenth) between each of the 4 sights.
86
85 // *************************************************** // Walk program // This program computes the mileage (rounded to nearest // tenth of mile) for each of 4 distances, given map // measurements on map with scale of 1 in = 0.25 mile // *************************************************** #include // for cout, endl #include // For setprecision using namespace std; float RoundToNearestTenth( float ); // declare function const float SCALE = 0.25; // Map scale (mi. per inch) C++ Program
87
86 C++ Code Continued const float DISTANCE1 = 1.5; // First map distance const float DISTANCE2 = 2.3; // Second map distance const float DISTANCE3 = 5.9; // Third map distance const float DISTANCE4 = 4.0; // Fourth map distance int main( ) { float totMiles; // Total of rounded miles float miles;// One rounded mileage cout.setf(ios::fixed, ios::showpoint); // use decimal format cout.setf(ios::floatfield); // print decimal points cout << setprecision(1); totMiles = 0.0;// Initialize total miles
88
87 // Compute miles for each distance on map miles = RoundToNearestTenth( DISTANCE1 * SCALE ); cout << DISTANCE1 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles; miles = RoundToNearestTenth( DISTANCE2 * SCALE ); cout << DISTANCE2 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles;
89
88 // Compute miles for other distances on map miles = RoundToNearestTenth( DISTANCE3 * SCALE ); cout << DISTANCE3 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles; miles = RoundToNearestTenth( DISTANCE4 * SCALE ); cout << DISTANCE4 << “ inches on map is “ << miles << “ miles in city.” << endl; totMiles = totMiles + miles;
90
89 cout << endl << “Total walking mileage is “ << totMiles << “ miles.” << endl; return 0 ;// Successful completion } // *************************************************** float RoundToNearestTenth ( /* in */ float floatValue) // Function returns floatValue rounded to nearest tenth. { return float(int(floatValue * 10.0 + 0.5)) / 10.0; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.