280 likes | 456 Views
Simple Data Types. Chapter 7. 7.1 Constants Revisited. Three reasons to use constants Constant is recognizable Compiler prevents changes in value Programming practices const type identifier = constant;. #define. An additional way to define constants
E N D
Simple Data Types Chapter 7
7.1 Constants Revisited • Three reasons to use constants • Constant is recognizable • Compiler prevents changes in value • Programming practices const type identifier = constant;
#define • 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;
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 and binary number • float stored in 2 parts plus the sign • sign - characteristic - mantissa • type float number = 2^characteristic * mantissa
Value Variations • 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
Value Variations • Three sizes of float • float • double • long double • Each uses a different amount of the computers memory • double is no less precise than float • long double provides less precision than double
Numerical Inaccuracies • Can have errors when using float in some computations • Do to the way floats are stored • Errors will be determined by the number of binary bits used in the mantissa • Arithmetic underflow and arithmetic overflow • Multiplying 2 small or large numbers together respectively
Ranges for int and float Constants • See table 7.1 • Definitions for some of these C++ constants are in the limits.h and float.h libraries • The actual values of these constants will vary from computer to computer
Mixing Types • The notion of type promotion • promoting a lower type to a higher type example: 3 + x /2 • if x is float constant would be promoted to float as well and actually be 2.0 • Type conversions • int to float (number.0) • float to int (truncation occurs)
Mixing Types • Example: int y; float x = 3.89; y = x; y would contain 3
Type Casting • Avoid mixing types but if you need to you can cast a type • Type casting allows you to change a type within the program for a specific function form: type (variable) average = sum / float (n); where n is declared as an int
7.3 Character Data and Functions • Character literal const char star = ‘*’; char nextLetter; nextLetter = ‘A’;
Character Representation • Bits required to store characters is based on the ASCII table (Appendix A) • Each character has an numeric code • 1 byte or 8 bits are typically used to represent characters
Relational Operators and Characters • Relational operators can be used with characters • Testing based on the characters ASCII value example: ‘0’ < ‘1’ True ‘A’ < ‘B’ True
Character Functions • ctype.h library provides many functions to the programmer • Table 7.2 lists many of the functions • Function name on the left and its purpose is listed to the right tolower (c) if c is uppercase, this function returns the corresponding lower case letter
collate.cpp // FILE: collate.cpp // PRINTS PART OF THE CHARACTER COLLATING // SEQUENCE #include <iostream> using namespace std; int main () { const int MIN = 32; const int MAX = 126; char nextChar;
collate.cpp // Display sequence of characters. for (int nextCode = MIN; nextCode <= MAX; nextCode++) { nextChar = char (nextCode); cout << nextChar; if (nextChar == 'Z') cout << endl; } return 0; }
collate.cpp Program Output Program output … !”#$%&`()*+,./0123456789;:<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^_’abcdefghijklmnopqrstuvwxyz{|}~.
7.4 Type bool Data and Logical Expressions • Used in assignment statements and logical expressions (True and False) • Complementing expressions < >= <= > > <= >= < == != != ==
Type bool Functions • bool function isdigit if (isdigit (ch)) cout << “You entered a number”; • bool return value from a function if (centsOverflow (cents)) { cents -= 100; dollars ++; }
Input and Output with bool • Can NOT be used for input or output • True represented by a numeric 1 • False represented by numeric 0 • Displaying bool values • cin.setf (ios::boolalpha); • cout.setf (ios::boolalpha);
7.5 Enumeration Types • Aid program readability • Represent various states example: enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday}; sunday has the value 0 monday has the value 1 and so on user-defined data type
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)
Enumeration Types • Characters • Switch statements • Comparisons • Write functions to read and write enumerated types (not know to compiler) • Discuss color.cpp
color.cpp // DISPLAYS THE VALUE OF thisColor void writeColor (color thisColor) { switch (thisColor) { case red: cout << "red"; break; case green: cout << "green"; break;
color.cpp case blue: cout << "blue"; break; case yellow: cout << "yellow"; break; default: status = 0; cerr << "*** ERROR: Invalid color value." << endl; } }
7.6 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)); • Mixing operators and operand types • float == char
Common Programming Errors • Operator Precedence errors • Watch use of parentheses to get correct precedence • ! Symbol • Enumeration types • Identifiers can only appear in list • Only use one value for each enumerated declaration