版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、3/18/20221Chapter 10. Simple Data Types: Built-in and Use-Defined3/18/20222C+ Data Typesstructuredarray struct union class addresspointer referencesimple integral enumchar short int long boolfloatingfloat double long double3/18/20223C+ Simple Data Typessimple typesintegralfloating char short int lon
2、g bool enum float double long doubleunsigned4Some Integral TypesType Size in BytesMinimum Value Maximum Valuechar1-128127short2-32,76832,767int2-32,76832,767long4-2,147,483,648 2,147,483,647NOTE: Values given for one machine. Actual sizes are machine-dependent.5Similarly, using two bytes ( = 16 bits
3、),216 = 65,536 DIFFERENT NUMBERS CAN BE REPRESENTED. If we wish to have only one number representing the integer zero, and half of the remaining numbers positive, and half negative, we can obtain the 65,536 numbers in the range below : -32,768 . . . . 0 . . . . 32,7670 1 0 0 1 0 1 00 1 1 0 0 0 1 13/
4、18/20226Range of Unsigned IntegersEach of n bits can have one of two values.Total # of patterns of n bits = 2 2 2 2n 2s= 2nIf n-bits are used to represent an unsigned integer value:Range: 0 to 2n-1 (2n different values)3/18/20227Range of Signed IntegersvHalf of the 2n patterns will be used for posit
5、ive values, and half for negative.vHalf is 2n-1.vPositive Range: 0 to 2n-1-1 (2n-1 patterns)vNegative Range: -2n-1 to -1 (2n-1 patterns)v8-Bits (n = 8): -27 (-128) to +27-1 (+127)3/18/20228Unsigned Overflow 1100(12) ( 7)10011Lost (Result limited by word size) 0011( 3) wrongValue of lost bit is 2n (1
6、6).16 + 3 = 19(The right answer!)3/18/20229Signed OverflowvOverflow is impossible when adding (subtracting) numbers that have different (same) signs.vOverflow occurs when the magnitude of the result extends into the sign bit position:v01111111 (0)10000000vThis is not rollover!3/18/202210Signed Overf
7、low-12010 100010002 -1710 sum: -13710 1011101112 011101112 (keep 8 bits) ( ) wrongNote: 119 28 = 119 256 = -13711Floating Point Types Type Size in BytesMinimum Maximum Positive Value Positive Valuefloat 43.4E-383.4E+38double 8 1.7E-3081.7E+308long double 103.4E-49321.1E NOTE: Values given for one ma
8、chine. Actual sizes are machine-dependent.12More about Floating Point Types(p367)floating point constants in C+ like 94.6 without a suffix are of type double by default to obtain another floating point type constant a suffix must be used the suffix F or f denotes float type, as in 94.6Fthe suffix L
9、or l denotes long double, as in 94.6L3/18/202213Floating-Point RealsThree components: significand 2exponent Sign An unsigned fractional valueA biased integer valueBase is implied313023220ExponentFractional Bits of Significand3/18/202214Example: -2.75 x 252302230310110 01000 01011 (Sign = Negative) +
10、 (Magnitude = 2.75 x 25) 10.112 x 25 1.0112 x 266 + 1273/18/202215Single-precision Floating-point Representation S Exp+127 Significand 2.000 0 10000000 (1).00000000000000000000000 1.000 0 01111111 (1).00000000000000000000000 0.750 0 01111110 (1). 00000 0.500 0 01111110 (1).00000000000000000000000 0.
11、000 0 00000000 (0).00000000000000000000000-0.501 1 01111110 (1).00000000000000000000000-0.751 1 01111110 (1). 00000-1.001 1 01111111 (1).00000000000000000000000-2.001 1 10000000 (1).000000000000000000000003/18/202216Fixed-Point Add/Subtract Using Operands w/Same Scale FactorsOperand/Result Bit Patte
12、rn IntegerScale Factor=ValueA00011.110+302-3 = 1/8 +3.750B00110.011+512-3 = 1/8 +6.375A + B01010.001+812-3 = 1/8+10.125A - B11101.011-212-3 = 1/8 -2.6253/18/202217Multiplying Fixed-Point Real NumbersOperand/ResultBit PatternIntScale FactorValueA0000000000011.110 302-3= 1/8 +3.7500B00000000001100.11
13、512-2= 1/4+12.7500A B .1101015302-3-2= 1/32+47.81253/18/202218Dividing Fixed-Point Real NumbersOperand/ResultBit PatternIntScale Factor=ValueA .1101015302-5 = 1/32+47.8125B0000000001110.0111152-3 = 1/8+14.3750A B00000000000011.01 =132-5+3= 1/4 +3.25003/18/202219Representational error P371vArithmetic
14、 error that occurs when the precision of the true result of an arithmetic operation is greater than the precision of the machine.20Header Files climits and cfloatvcontain constants whose values are the maximum and minimum for your machine v vsuch constants are FLT_MAX, FLT_MIN, LONG_MAX, LONG_MIN#in
15、clude using namespace std ;.cout “Maximum long is “ LONG_MAX endl ; cout “Minimum long is “ LONG_MIN endl ;3/18/202221Contents of #define SCHAR_MIN -127#define SCHAR_MAX 127#define SHRT_MIN -32767#define SHRT_MAX 32767#define INT_MIN -2147483647#define INT_MAX 2147483647#define LONG_MIN -2147483647#
16、define LONG_MAX 2147483647 3/18/202222Choosing Numeric Data TypevIn general, int is preferable.vUse long only if the range of int values on your machine is to restrictive.vUse double and long double only if you need enormously large of small numbers, or if your machines float values do nor carry eno
17、ugh digits of precision.vAvoid the unsigned forms of integral types.23By definition, the size of a C+ char value is always 1 byte. exactly one byte of memory spaceSizes of other data type values in C+ are machine-dependent. A24Using one byte ( = 8 bits ), HOW MANY DIFFERENT NUMBERS CAN BE REPRESENTE
18、D USING 0s and 1s?Each bit can hold either a 0 or a 1. So there are just two choices for each bit, and there are 8 bits. 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 28 = 2560 1 1 0 0 0 1 125ASCII and EBCDICvASCII (pronounced ask-key) and EBCDIC are the two character sets commonly used to represent characters in
19、ternally as integers vASCII is used on most personal computers, and EBCDIC is used mainly on IBM mainframes vusing ASCII the character A is internally stored as integer 65. Using EBCDIC the A is stored as 193. In both sets, the successive alphabet letters are stored as successive integers. This enab
20、les character comparisons with A less than B, etc.26 LeftDigit(s) 3 ” ! “ # $ % & 4 ( ) * + , - . / 0 1 5 2 3 4 5 6 7 8 9 : ; 6 ? A B C D E 7 F G H I J K L M N O 8 P Q R S T U V W X Y 9 Z _ a b c 10 d e f g h I j k l m 11 n o p q r s t u v w 12 x y z | Right DigitASCII (Printable) Character Set
21、0 1 2 3 4 5 6 7 8 9 27Incrementing char Variablevbecause char variables are stored internally as integers, they can be incremented and compared vEXAMPLEvvchar ch;v/ loop to print out letters A thru Zvfor (ch = A ; ch = Z ; ch+ )vvcout ch ;v28Control Charactersvin addition to the printable characters
22、, character sets also have nonprintable control characters to control the screen, printer, and other hardware vin C+ programs, control characters are represented by escape sequences. Each escape sequence is formed by a backslash followed by one or more additional characters 29Some Escape SequencesnN
23、ewline (Line feed in ASCII)tHorizontal tabbBackspaceaAlert (bell or beep)BackslashSingle quote (apostrophe)”Double quote (quotation mark)0Null character (all zero bits)dddOctal equivalent (3 octal digits)xdddHexadecimal equivalent (1 or more hex digits for integer value of character)30Converting cha
24、r digit to int vthe successive digit characters 0 through 9 are represented in ASCII by the successive integers 48 through 57 (the situation is similar in EBCDIC)vas a result, the following expression converts a char digit value to its corresponding integer value v 2 ?v ch numberv char ch ;vint numb
25、er ;v. . .vnumber = int ( ch - 0 ) ;/ using explicit type cast31Character Function Prototypesin int toupper ( int ch );/ FUNCTION VALUE /= uppercase equivalent of ch, if ch is a lowercase letter / = ch, otherwiseint tolower ( int ch );/ FUNCTION VALUE /= lowercase equivalent of ch, if ch is an upper
26、case letter / = ch, otherwiseNOTE: Although parameter and return type are int, in concept these functions operate on character data.32Reading a Yes or No User Responsestring inputStr ;.cout inputStr ;if ( toupper ( inputStr 0 ) = Y ) / First letter was Y.else if ( toupper ( inputStr 0 ) = N ) / Firs
27、t letter was N.elsePrintErrorMsg ( ) ;3/18/202233Additional C+ Operators P352vAssignment Operators and Assignment ExpressionsvIncrement and Decrement OperatorsvBitwise OperatorsvThe Cast OperationvThe sizeof OperationvThe ? : Operator3/18/202234Bitwise OperatorsvBitwise operators operate on individu
28、al bit positions within the operandsvThe result in any one bit position is entirely independent of all the other bit positions. 3/18/202235Bitwise Expressions(5 | 3) & 6= (00.0101 OR 00.0011) AND 00.0110= (00.0101 OR 11.1100) AND 00.0110= (11.1101) AND 00.0110= 00.0100= 43/18/202236Interpreting
29、the Bitwise-ANDmpm AND pInterpretation0 001 00If bit m of the mask is 0,bit p is cleared to 0 inthe result.0 011 1pIf bit m of the mask is 1,bit p is passed throughto the result unchanged.3/18/202237Interpreting the Bitwise-ORmpm OR pInterpretation0 001 1pIf bit m of the mask is 0,bit p is passed th
30、roughto the result unchanged.0 111 11If bit m of the mask is 1,bit p is set to 1 inthe result.3/18/202238Interpreting the Bitwise-XORmpm XOR pInterpretation0 001 1pIf bit m of the mask is 0,bit p is passed throughto the result unchanged.0 111 0pIf bit m of the mask is 1,bit p is passed throughto the
31、 result inverted.3/18/202239Testing BitsvA 1 in the bit position of interest is ANDed with the operand. The result is non-zero if and only if the bit of interest was 1:vif (bits & 64) != 0)/* check to see if bit 6 is set */01000000b7b6b5b4b3b2b1b00b6000000&3/18/202240Testing BitsSince any no
32、n-zero value is interpreted as true, the redundant comparison to zero may be omitted, as in:if (bits & 64) /* check to see if bit 6 is set */3/18/202241vThe mask (64) is often written in hex (0 x0040), but a constant-valued shift expression provides a clearer indication of the bit position being
33、 tested:vif (bits & (1 6) /* check to see if bit 6 is set */vAlmost all compilers will replace such constant-valued expressions by a single constant, so using this form almost never generates any additional code.Testing Bits3/18/202242Setting BitsvSetting a bit to 1 is easily accomplished with t
34、he bitwise-OR operator:vbits = bits | (1 7) ;/* sets bit 7 */vThis would usually be written more succinctly as:v bits |= (1 7) ;/* sets bit 7 */10000000b7b6b5b4b3b2b1b01b6b5b4b3b2b1b0|3/18/202243Setting BitsvNote that we dont add (+) the bit to the operand! That only works if the current value of th
35、e target bit in the operand is known to be 0. vAlthough the phrase set a bit to 1 suggests that the bit was originally 0, most of the time the current value of the bit is actually unknown. 3/18/202244vClearing a bit to 0 is accomplished with the bitwise-AND operator:vbits &= (1 7) ; /* clears bi
36、t 7 */vNote that we dont subtract the bit from the operand!Clearing Bits (1 7)10000000(1 7)011111113/18/202245vWhen clearing bits, you have to be careful that the mask is as wide as the operand. For example, if bits is changed to a 32-bit data type, the right-hand side of the assignment must also be
37、 changed, as in:v bits &= (1L 7) ; /* clears bit 7 */Clearing Bits3/18/202246vInverting a bit (also known as toggling) is accomplished with the bitwise-XOR operator as in:vbits = (1 6) ; /* flips bit 6 */vAlthough adding 1 would invert the target bit, it may also propagate a carry that would mod
38、ify more significant bits in the operand.Inverting Bits47typedef statement vtypedef creates an additional name for an already existing data type v vbefore bool type became part of ISO-ANSI C+, a Boolean type was simulated this way typedef int Boolean;const Boolean true = 1 ;const Boolean false = 0 ;
39、.Boolean dataOK ;.dataOK = true ;3/18/202248C+ Data Typesstructuredarray struct union class addresspointer referencesimple integral enumchar short int long boolfloatingfloat double long double49Enumeration Types vC+ allows creation of a new simple type by listing (enumerating) all the ordered values
40、 in the domain of the type v EXAMPLEenum MonthType JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ;name of new typelist of all possible values of this new type50enum Type Declarationenum MonthType JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ;vthe enum declaration creates a
41、 new programmer-defined type and lists all the possible values of that type-any valid C+ identifiers can be used as values vthe listed values are ordered as listed. That is, JAN FEB MAR APR , and so on vyou must still declare variables of this type 51Declaring enum Type Variablesenum MonthType JAN,
42、FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ;MonthType thisMonth; / declares 2 variables MonthType lastMonth; / of type MonthTypelastMonth = OCT ; / assigns valuesthisMonth = NOV ;/ to these variables.lastMonth = thisMonth ;thisMonth = DEC ;52Storage of enum Type Variablesenum MonthType JA
43、N, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ;stored as 0 stored as 1 stored as 2 stored as 3 etc. stored as 11 53Use Type Cast to Incrementenum Type Variablesenum MonthType JAN, FEB, MAR, APR, MAY, JUN,JUL, AUG, SEP, OCT, NOV, DEC ;MonthType thisMonth;MonthType lastMonth; lastMonth = OC
44、T ; thisMonth = NOV ;lastMonth = thisMonth ;thisMonth = thisMonth+ ; / COMPILE ERROR !thisMonth = MonthType( thisMonth + 1) ; / uses type cast54More about enum TypeEnumeration type can be used in a Switch statement for the switch expression and the case labels.Stream I/O ( using the insertion operat
45、ors ) is not defined for enumeration types. (cout int)Instead, functions can be written for this purpose.Comparison of enum type values is defined using the 6 relational operators ( , , = , = , != ).An enum type can be the return type of a value-returning function in C+. SOME EXAMPLES . . .3/18/2022
46、55enum Typevvoid main( )venum MonthType JAN, FEB, MAR, APR, MAY, JUN,v JUL, AUG, SEP, OCT, NOV, DEC ;vMonthType a;va=(MonthType)1;vcouta;vvOutput is : 1v枚举类型到数值可以隐式类型转化,数值到枚举类型不可以隐式类型转化。枚举类型到数值可以隐式类型转化,数值到枚举类型不可以隐式类型转化。56MonthType thisMonth;switch ( thisMonth ) / using enum type switch expression ca
47、se JAN :case FEB :case MAR : cout “Winter quarter” ; break ;case APR : case MAY :case JUN : cout “Spring quarter” ; break ; case JUL :case AUG :case SEP : cout “Summer quarter” ; break ; case OCT : case NOV :case DEC : cout “Fall quarter” ;57Using enum type Control Variable with for Loopenum MonthTy
48、pe JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC ;void WriteOutName ( /* in */ MonthType ) ; / prototype. .MonthType month ;for (month = JAN ; month = DEC ; month = MonthType (month + 1 ) )/ requires use of type cast to incrementWriteOutName ( month ) ; / function call to perform output
49、 .58void WriteOutName ( /* in */ MonthType month )/ Prints out calendar name corresponding to month/ Precondition: month is assigned/ Postcondition: calendar name for month has been written outswitch ( month ) case JAN : cout “ January ” ; break ;case FEB : cout “ February ” ; break ;case MAR : cout
50、 “ March ” ; break ;case APR : cout “ April ” ; break ; case MAY : cout “ May ” ; break ;case JUN : cout “ June ” ; break ; case JUL : cout “ July ” ; break ;case AUG : cout “ August ” ; break ;case SEP : cout “ September ” ; break ; case OCT : cout “ October ” ; break ; case NOV : cout “ November ”
51、 ; break ;case DEC : cout “ December ” ; break ;59enum SchoolType PRE_SCHOOL, ELEM_SCHOOL, MIDDLE_SCHOOL, HIGH_SCHOOL, COLLEGE ;.SchoolType GetSchoolData ( void )/ Obtains information from keyboard to determine school level/ Postcondition: Function value = personal school levelSchoolType schoolLevel
52、 ; int age ;int lastGrade ; cout age ;Function with enum type Return Value 60if ( age 6 ) schoolLevel = PRE_SCHOOL ;elsecout lastGrade;if ( lastGrade 5 )schoolLevel = ELEM_SCHOOL ;else if ( lastGrade 8 )schoolLevel = MIDDLE_SCHOOL ;else if ( lastGrade 12 )schoolLevel = HIGH_SCHOOL ;else schoolLevel
53、= COLLEGE ; return schoolLevel ;/ return enum type value61Multifile C+ Programs vC+ programs often consist of several different files with extensions such as .h and .cppvrelated typedef statements, const values, enum type declarations, and similar items are often placed in user-written header files
54、vby using the #include preprocessor directive the contents of these header files are inserted into any program file that uses them 62Inserting Header Files #include / iostream #include “school.h” int main ( ) enum SchoolType PRE_SCHOOL, . ELEM_SCHOOL, . MIDDLE_SCHOOL,. HIGH_SCHOOL, COLLEGE ; 63Impli
55、cit type coercion occurs . . . whenever values of different data types are used in: 1. arithmetic and relational expressions2. assignment operations3. parameter passage4. returning a function value with return(from a value-returning function)TWO RULES APPLY . . .64Promotion (or widening) in C+. . .
56、is the conversion of a value from a “lower” type to a “higher” type-specifically, for mixed type expressions:Step 1. Each char, short, bool, or enumeration value is promoted to int. If both operands are now int, the result is an int expression.Step 2. If Step 1 leaves a mixed-type expression, the fo
57、llowing precedence of types is used (from lowest to highest):int, unsigned int, long, unsigned long, float, double, long doubleThe value of the operand of “lower” type is promoted to that of the “higher” type. For an arithmetic expression, the result is an expression of that higher type. For a relat
58、ional expression, the result is always bool (true or false).65is the conversion of a value from a “higher” type to a “lower” type, and may cause loss of information FOR EXAMPLE, 98.6 98 temperature number float temperature = 98.6 ; int number ; number = temperature ; / demotion occurs Demotion (or n
59、arrowing) . . . 3/18/202266TRUE/FALSE The statement char someChar = ; stores the apostrophe (single quote) character into someChar. A)TrueB)False 3/18/202267TRUE/FALSEvTRUE3/18/202268TRUE/FALSE The call to the library function tolower(someChar)returns g if someChar is G but returns an unknown value
60、if someChar is #. A)TrueB)False 3/18/202269TRUE/FALSEvFALSE3/18/202270TRUE/FALSE The code segment string str = HI!; cout str1; outputs the single character I. A)TrueB)False 3/18/202271TRUE/FALSEvTRUE3/18/202272TRUE/FALSE The values of a C+ enumeration type may be input directly. A)TrueB)False3/18/202273TRUE/FALSEvFALSE3/18/2022
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年停车场管理权委托合同
- 2024年就业协议书样本
- 2024年施工补充协议范本
- 2024年联合办学协议书
- 2024年铺面房屋租赁协议
- 2024年的简单装修合同文本模板
- 2024年进料加工贸易合同(格式)
- 2024年和解协议书范本900字
- 2024年碎石运输协议范本
- 2024年抵押贷款合同公证
- 13、停电停水等突发事件的应急预案以及消防制度
- 医疗HRP整体解决方案课件
- 【知识点解析】抛物线的光学性质及其应用
- 冠心病介入治疗技术医疗质量控制指标(2021年版)可编辑版
- 分布式光伏安装清包合同
- Unit 3 Reading 1 friendship on the rocks课件-高中英语牛津译林版必修第一册
- 四机厂介绍企业介绍
- 自动门及门禁系统整体解决方案自助银行门禁系统专业网
- 综合科学科教研活动记录表
- 数量词病句课件
- 人教版七年级上册语文第一单元测试卷及答案(常用)
评论
0/150
提交评论