Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Simple Data Types Problem Solving, Abstraction, and Design using.

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Simple Data Types Problem Solving, Abstraction, and Design using."— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Simple Data Types Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman

2 2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.1 Constants Revisited Reasons to use constants –constants are named, so easy to understand –compiler prevents accidental change in value –good programming practice for preventing errors and making code more readable General form const type identifier = constant;

3 3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley #define Compiler Directive An additional way to define constants Used in older C programs prior to introduction of constants #define identifier replacement-text #define pi 3.14159 The same as const float pi = 3.14159;

4 4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.2 Internal Representations of int and float float and int used to represent numbers Stored differently in the computer int stored as binary 1s and 0s –sign bit and value as binary number float stored in 2 parts plus the sign sign - characteristic - mantissa float-number = mantissa  2 characteristic

5 5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Integer Types Three sizes of int –short int –int –long int Each uses a different amount of the computers memory –long and short provide consistency between compilers –short can save lots of memory

6 6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Floating-Point Types Three sizes of float –float –double –long double Each uses a different amount of the computer’s memory –double is no less precise than float –long double provides more precision than double

7 7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Types of Numeric Literals If the literal has a decimal point, it’s of type float A literal without a decimal point is an integer (type int)

8 8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Table 7.1 Special C++ Constants

9 9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Numerical Inaccuracies Can have representational errors when using float in some computations, due to the way floats are stored –some real numbers cannot be represented accurately (e.g. 1/3) –conversion from fractional decimal to binary not always precise –Depends on the number of binary bits used in the mantissa Cancellation error when combining large and small numbers Arithmetic underflow and arithmetic overflow –E.g. multiplying two small or large numbers together, respectively

10 10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Mixed Types: Promotions Allowed to mix certain types in expressions, assignments, and argument passing The compiler must examine operations involved with each operation and convert (promote) mixed operands to make them all the same Integer types are promoted to floating-point types when mixed

11 11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Conversions Conversions meant to be value preserving x = 2;// float x Truncation can occur i = 3.89;// int i ch = 64.97;// char ch printInt(27.7);// void printInt(int)

12 12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Casting In addition to automatic conversion, can force conversion using a cast average = float(sum) / float(n); where sum and n are type int. Note: NOT average = float(sum / n);

13 13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.3 Character Data and Functions char type can contain exactly one character Literal consists of character surrounded by single quotation marks. E.g. const char STAR = ‘*’; const char ENDLINE = ‘\n’; char nextLetter; nextLetter = ‘A’;

14 14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Character Representation Each character has a unique numeric code The bits required to store characters is based on the ASCII table (Appendix A) 1 byte (8 bits) are typically used to represent characters (rightmost 7 bits are the code, extra bit usually ignored) Can convert between char and int types.

15 15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Useful Character Functions char tolower(char); char toupper(char); bool isalpha(char); bool isdigit(char) bool islower(char); bool isspace(char); bool isupper(char);

16 16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.2 Function digitToNumber

17 17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.4 Type bool Data and Logical Expressions bool type values are true and false Complementing logical expressions can be done in 2 ways –using logical operator ! (not) –using DeMorgan’s Theorem

18 18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The ! (not) Operator Useful in writing if and while conditions –can simplify the expression –can make expression more readable Complements of relational operators: <>= >=< = =!= ><= !== =

19 19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DeMorgan’s Theorem !(exp 1 && exp 2 ) is the same as exp 1 || exp 2 !(exp 1 || exp 2 ) is the same as exp 1 && exp 2

20 20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Input and Output of bool Data bool data displays 0 for false and 1 for true Must enter 0 for false and 1 for true for input of bool value Don’t usually want to read/write boolean values Can enter/print false and true for bool data: cin.setf(ios::boolalpha); cout.setf(ios::boolalpha);

21 21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.5 Enumeration Types Aid program readability Associates integer values with new programmer- defined values E.g.: enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; Enumerator sunday has the value 0, monday has the value 1, and so on

22 22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Enumeration Type Declarations enum enumeration-type {enumerator-list}; enum classId {freshman, sophomore, junior, senior}; classId newClass; if (newClass == freshman) do something else if (newClass == sophomore)...

23 23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparisons Involving Enumeration Types The order relationship is determined by the order of enumerators in the list sunday < monday wednesday != tuesday wednesday == wednesday thursday > monday Cannot mix enumeration types entertainment != monday

24 24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Reading and Writing Enumeration Type Values Can’t read/write directly, must use own functions Consider definitions enum color {red, green, blue, yellow}; color eyeColor = blue; and function call writeColor(eyeColor);

25 25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.4 Function to display a value of type color void writeColor (color thisColor) // IN: color to display as a string { // Display color value as a string. switch (thisColor) { case red: cout << “red “; break; case green: cout << “green “; break; case blue: cout << “blue “; case yellow: cout << “yellow “; break; default: cout << “*** ERROR: Invalid color value.” << endl; }

26 26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.5 Function to read a value of type color

27 27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Program Style Usually end switch case with a break statement For a switch in a function, may want to replace each break with a return statement

28 28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Placement of Enumeration Type Declarations Normally want enumeration types to be available to multiple functions Good practice to declare enumeration types before function prototypes Doing so causes enumeration types to have global scope

29 29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Section 7.6 Iterative Approximations Fig. 7.1 An equation f(x) with six roots (f(x) = 0)

30 30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.8 Using a Function Parameter // Displays value of f(x) at x = x1, x2, // and x3 void evaluate( double f(double), // IN: the function // to evaluate double x1, // IN: argument for first call double x2, // IN: argument for second call double x3) // IN: argument for third call { cout << f(x1) << ", " << f(x2) << ", " << f(x3) << endl; }

31 31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 7.2 Change of Sign Implies an Odd Number of Roots

32 32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 7.3 Three Possibilities That Arise When the Interval [xleft, xright] Is Bisected

33 33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Bisection algorithm 1. Set error flag to true if the interval contains an even number of roots and return –999.0 if error flag is true. 2. Repeat as long as the interval is greater than tolerance and the root is not found 3. Compute the function value at the midpoint 4. if function value at xMid is zero Root is found – return xMid. else if the root is in the left half of the interval Reset xRight to xMid. else if the root is in the right half of the interval Reset xMid to xRight. 5. Return the midpoint of the final interval.

34 34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.9 function main // File: bisect.cpp // Finds the root of a function using the bisection method #include using namespace std; // Function prototypes double bisect(double, double, double, double f(double), bool&); double f(double); int main() { double xLeft, xRight; // end points of interval double epsilon; // error tolerance double root; // root found by bisect bool error; // error flag // Get endpoints and tolerance cout << "Enter interval endpoints: "; cin >> xLeft >> xRight; cout << "Enter tolerance: "; cin >> epsilon;

35 35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.9 function main cont’d // Use bisect function to look for root of function f root = bisect(xLeft, xRight, epsilon, f, error); // Display result if (!error) cout << "Root found at " << root << "\nValue of f(x) at root is: " << f(root); else cout << "There may be no root in [" << xLeft << ", " << xRight << "]" << endl; return 0; }

36 36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.9 function bisect // Implements bisection method to find a root of function f // in interval [xLeft, xRight]. // PRE: xLeft, xRight, and epsilon are defined. // POST: Returns midpoint of xLeft and xRight if the difference // between these values is <= epsilon. Returns true to // error if there is no root. double bisect( double xLeft, // IN: endpoints of interval double xRight, // for possible root double epsilon, // IN: error tolerance double f(double), // IN: the function bool& error) // OUT: error flag { double xMid; // midpoint of interval double fLeft, fRight; // function values at xLeft, xRight, double fMid; // and xMid // Compute function values at initial endpoints of interval fLeft = f(xLeft); fRight = f(xRight); // If no change of sign in the interval, there is no unique root error = (fLeft * fRight) > 0; // test for same sign - set error if (error) return -1.0; // no root - return to caller

37 37 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.9 function bisect cont’d // Repeat while interval > error tolerance while (fabs(xLeft - xRight) > epsilon) { // Compute function value at midpoint xMid = (xLeft + xRight) / 2.0; fMid = f(xMid); // Test function value and reset interval if root not found if (fMid == 0.0) // xMid is the root return xMid; // Return the root else if (fLeft * fMid < 0.0) // root in [xLeft, xMid] xRight = xMid; else // root in [xMid, xRight] xLeft = xMid; // Display next interval cout << "New interval is [" << xLeft << ", " << xRight << "]" << endl; } // Return midpoint of last interval return (xLeft + xRight) / 2.0; }

38 38 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function f and sample run double f(double x) { return 5 * pow(x, 3.0) - 2 * pow(x, 2.0) + 3; } Enter interval endpoints: -1.0 1.0 Enter tolerance: 0.00001 New interval is [-1, 0] New interval is [-1, -0.5] New interval is [-0.75, -0.5] New interval is [-0.75, -0.625] New interval is [-0.75, -0.6875] New interval is [-0.75, -0.71875] New interval is [-0.734375, -0.71875] New interval is [-0.734375, -0.726562]... New interval is [-0.729004, -0.728882] New interval is [-0.729004, -0.728943] New interval is [-0.729004, -0.728973] New interval is [-0.729004, -0.728989] New interval is [-0.729004, -0.728996] Root found at -0.729 Value of f(x) at root is: 1.45582e-05

39 39 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.7 User Input for a graphics program The following program draws a collection of shapes whose kind (circle, square, or ellipse) and position is selected by the user (See Fig. 7.1). Within the main loop body, the statement drawShape(shapeCh); calls function drawShape to draw the shape which is read into shapeCh.

40 40 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley User Input for a graphics program cont’d Function drawShape prompts the user to click the mouse to set the desired position of the shape. The statement clearmouseclick(WM_LBUTTONDOWN); clears any left mouse button clicks (WM_LBUTTONDOWN) that may haveoccurred in the past. The while loop while (!ismouseclick(WM_LBUTTONDOWN)) { delay(PAUSE); } continues executing (pausing the program) until the user clicks the left mouse button. The predefined graphics constant WM_LBUTTONDOWN means that the focus is on left-mouse button events.

41 41 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley User Input for a graphics program cont’d After the mouse click occurs, the call to function outtextxy "erases" the prompt to click the mouse by overwriting it in black. The statement getmouseclick(WM_LBUTTONDOWN, x, y); stores in x and y (function output parameter) the coordinates of the mouse when it was clicked. The shape size and color are selected randomly and the switch statement draws the shape selected by shapeCh.

42 42 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.10 int main() { int width; // width of screen int height; // height of screen char shapeCh; // specifies kind of shape width = getmaxwidth(); height = getmaxheight(); initwindow(width, height, "Position Shapes"); outtextxy(100, 10, "SELECT SHAPE BY TYPING A CHARACTER IN BRACKETS BELOW -- C, S, E, OR Q"); outtextxy(100, 30, "[C]IRCLE | [S]QUARE) | [E]LLIPSE | [Q]UIT"); // Draw shapes until user selects QUIT shapeCh = toupper(getch()); // Get character from keyboard while (shapeCh != 'Q') { drawShape(shapeCh); // Draw shape shapeCh = toupper(getch()); // Get next shape } closegraph(); return 0; }

43 43 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.10 cont’d // Draw the selected shape void drawShape (char shapeCh) // IN: shape to display or Q to quit { const int PAUSE = 100; // time to display frame int x, y; // shape center point // Wait for mouse click outtextxy(100, 50, "POSITION SHAPE BY CLICKING MOUSE"); clearmouseclick(WM_LBUTTONDOWN); while (!ismouseclick(WM_LBUTTONDOWN)) { delay(PAUSE); } setcolor (BLACK); // Overwrite mouse click prompt outtextxy(100, 50, "POSITION SHAPE BY CLICKING MOUSE "); // Set shape size and color randomly getmouseclick(WM_LBUTTONDOWN, x, y); int size = rand() % 100 + 20; // 20 <= size <= 119 int color = rand() % 15 + 1; // 1 <= color <= 15 setcolor(color); setfillstyle(SOLID_FILL, color);

44 44 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Listing 7.10 cont’d // Draw shape selected by user at mouse position (x, y) switch (shapeCh) { case 'C' : fillellipse(x, y, size, size); break; case 'S' : bar(x - size/2, y - size/2, x + size/2, y + size/2); break; case 'E' : fillellipse(x, y, size, size / 2); break; case 'Q' : outtextxy(100, 50, "CLOSING WINDOW"); return; default: outtextxy(100, 50, "NOT A VALID SHAPE"); return; }

45 45 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Positioned Shapes

46 46 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.8 Common Programming Errors Omitting pairs of parentheses m = y2 - y1 / x2 - x1; Compiler will not complain but calculation will be in error Unbalanced parentheses z = sqrt (x + y) / (1 + sqrt (x + y)); Incorrectly mixing operators and operand types

47 47 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Common Programming Errors Operator Precedence errors –Watch use of parentheses to get correct precedence –! symbol has high precedence Using enumeration types –Identifiers only must appear in list –Enumerator must appear in only one list –Don’t use quote marks around enumerators


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Simple Data Types Problem Solving, Abstraction, and Design using."

Similar presentations


Ads by Google