C++程序设计课件:Chapter3 Numeric Types, Expressions, and Output_第1页
C++程序设计课件:Chapter3 Numeric Types, Expressions, and Output_第2页
C++程序设计课件:Chapter3 Numeric Types, Expressions, and Output_第3页
C++程序设计课件:Chapter3 Numeric Types, Expressions, and Output_第4页
C++程序设计课件:Chapter3 Numeric Types, Expressions, and Output_第5页
已阅读5页,还剩87页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、11/29/2021C+程序设计 教师:1Chapter 3 Numeric Types, Expressions, and OutputnC+ built-in data types are organized into simple types, structured types, and address types. 11/29/2021C+程序设计 教师:2C+ Data Typesstructuredarray struct union class addresspointer referencesimple integral enumchar short int long bool

2、floatingfloat double long double11/29/2021C+程序设计 教师:3C+ Simple Data Typessimple typesintegralfloating char short int long bool enum float double long doubleunsigned11/29/2021C+程序设计 教师:4Standard Data Types in C+nIntegral Typesnrepresent whole numbers and their negativesndeclared as int, short, or lon

3、gnFloating Typesnrepresent real numbers with a decimal pointndeclared as float, or doublenCharacter Typenrepresents single charactersndeclared as char11/29/2021C+程序设计 教师:5Samples of C+ Data Valuesint sample values 4578 -45780float sample values95.27495.2659521E-3-95E-195.213E2char sample values B d

4、4? *11/29/2021C+程序设计 教师:6 About Integral TypesnThe types char, short, int, long are intended to represent different sizes of integers. The sizes are machine dependent. sizeof operator can be used to determine type sizes in your machine. n e.g. sizeof(int) is int types size in byte.n sizeof(char)=siz

5、eof(short)= sizeof(int)= sizeof(long)nIn a 32-bit machine : n char : 1 byte -128,127 n short : 2 byte -32768,32767 n int : 4 byte -2147483648, 2147483647 n long : 4 byte -2147483648, 2147483647 nMost compilers dont give error message when integer overflow occurs. e.g. INT_MAX +1 INT_MIN11/29/2021C+程

6、序设计 教师:7int type literalsnDecimaln 22 16 1 498 0 4600 -378 -912nOctaln 022 015nHexadecimaln 0 xFF 0X1011/29/2021C+程序设计 教师:8Scientific Notation 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.02.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.0002711/29/2021C+程序设计 教师:9More About Floating Point Valuesnfloating point num

7、bers 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 nEXAMPLES 18.4 500. .8 -127.358 nalternatively, floating point values can have an exponent, as in scientific notation-the number preceding th

8、e letter EEXAMPLES 1.84E1 5E2 8E-1 -.127358E311/29/2021C+程序设计 教师:10Arithmetic Operators P73nUnary : +(plus) -(minus)nBinary: + - * /(integral,floating-point )n %(modulus)(integral only)n -3%2 /-1n7.0/2.0 / 3.5 double/double doublen7/2 / 3 int/int int11/29/2021C+程序设计 教师:11Division Operator P75nthe re

9、sult of the division operator depends on the type of its operands nif one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type nExamples11 / 4 has value 211.0 / 4.0 has value 2.7511 / 4.0 has value 2.7511/29/2021C+程序设计 教师:12Main re

10、turns an int value tothe operating system/*/ FreezeBoil program/ This program computes the midpoint between/ the freezing and boiling points of water/*#include using namespace std;const float FREEZE_PT = 32.0 ; / Freezing point of waterconst float BOIL_PT = 212.0 ; / Boiling point of waterint main (

11、 ) float avgTemp ; / Holds the result of averaging / FREEZE_PT and BOIL_PT11/29/2021C+程序设计 教师:13Function main Continued cout “Water freezes at “ FREEZE_PT endl ; cout “ and boils at “ BOIL_PT “ degrees.” endl ; avgTemp = FREEZE_PT + BOIL_PT ; avgTemp = avgTemp / 2.0 ; cout “Halfway between is “ ; co

12、ut avgTemp “ degrees.” endl ; return 0 ;11/29/2021C+程序设计 教师:14Modulus Operatornthe modulus operator % can only be used with integer type operands and always has an integer type result nits result is the integer type remainder of an integer division EXAMPLE11 % 4 has value 3 because)411R = 211/29/202

13、1C+程序设计 教师:15More C+ Operators8int age;age = 8;age = age + 1; age9age11/29/2021C+程序设计 教师:16PREFIX FORMIncrement Operator8int age;age = 8;+age; age9age11/29/2021C+程序设计 教师:17POSTFIX FORM Increment Operator8int age;age = 8;age+; age9age11/29/2021C+程序设计 教师:18Decrement Operator100int dogs;dogs = 100;dogs

14、-; dogs99dogs11/29/2021C+程序设计 教师:19Which Form to Usenwhen the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variables value, it can be used in either prefix or postfix form dogs- ; -dogs ;USE EITHER11/29/2021C+程序设计 教师:20BUT.nwhen th

15、e increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results WELL SEE HOW LATER . . .11/29/2021C+程序设计 教师:21Increment and Decrement Operators nDifference between suffix and prefix:nSuffix: expression(num+) value is original

16、value of the operand. nPrefix: expression(+num) value is new value of the operand. ne.g. nint num=10; ncout num+ num;/ 10 10ncout num+; cout num;/ 11 12nint num=10; ncout +num num;/ 11 10ncout +num; cout b? 1:211/29/2021C+程序设计 教师:24Some C+ OperatorsPrecedence OperatorDescription Higher ( )Function c

17、all +Positive -Negative *Multiplication / Division %Modulus (remainder) +Addition -SubtractionLower = Assignment11/29/2021C+程序设计 教师:25Precedencenhigher Precedence determines which operator is applied first in an expression having several operators np684 Appendix B11/29/2021C+程序设计 教师:26Associativityn

18、left to right Associativity means that in an expression having 2 operators with the same priority, the left operator is applied first nin C+ the binary operators * , / , % , + , - are all left associative nexpression 9 - 5 - 1 means ( 9 - 5 ) - 14 - 1 311/29/2021C+程序设计 教师:277 * 10 - 5 % 3 * 4 + 9mea

19、ns (7 * 10) - 5 % 3 * 4 + 9 70 - 5 % 3 * 4 + 970 - (5 % 3) * 4 + 9 70 - 2 * 4 + 9 70 - ( 2 * 4 ) + 9 70 - 8 + 9 ( 70 - 8 ) + 9 62 + 9 71Evaluate the Expression11/29/2021C+程序设计 教师:28Parenthesesnparentheses can be used to change the usual ordernparts in ( ) are evaluated firstnevaluate (7 * (10 - 5) %

20、 3) * 4 + 9 ( 7 * 5 % 3 ) * 4 + 9 ( 35 % 3 ) * 4 + 9 2 * 4 + 9 8 + 9 1711/29/2021C+程序设计 教师:29nType Coercion - The implicit (automatic) conversion of a value from one type to another.nType Casting - The explicit conversion of a value from one type to another.nConversions may take place in assignments

21、, initializations and mixed types mode expressions .11/29/2021C+程序设计 教师:30Variable = Expressionnfirst, Expression on right is evaluatednthen 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 store

22、d if the types differ for Expression and VariableAssignment Operator Syntax11/29/2021C+程序设计 教师:31What value is stored?float a;float b;a = 8.5;b = 9.37;a = b;abab8.59.37?11/29/2021C+程序设计 教师:32What is stored? float someFloat; someFloat someFloat = 12;/ causes implicit type conversionsomeFloat12.011/29

23、/2021C+程序设计 教师:33What is stored? int someInt; someInt someInt = 4.8;/ causes implicit type conversionsomeInt411/29/2021C+程序设计 教师:34n Type casting: n form1: typename(expression) n form2: (typename)expressionn Convert from type of expression to type denoted by typenamen someFloat = float(3*someInt +2)

24、; / int float n someFloat = (float)(3*someInt +2); / int float n someInt = int(5.2 / someFloat anotherFloat); / double intn someInt = int(someFloat +0.5) ; / double int n /rounding off floating-point number11/29/2021C+程序设计 教师:35Type Casting is Explicit Conversion of Typeint(4.8) has value4float(5)ha

25、s value5.0float(7/4)has value1.0float(7) / float(4) has value1.7511/29/2021C+程序设计 教师:36Some Expressionsint age;EXAMPLEVALUEage = 8 8- age- 85 + 8135 / 8 06.0 / 5.01.2float ( 4 / 8 )0.0float ( 4 ) / 80.511/29/2021C+程序设计 教师:37Function Concept in Math f ( x ) = 5 x - 3When x = 1, f ( x ) = 2 is the ret

26、urned 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 functionParameter of functionFunction definition11/29/2021C+程序设计 教师:3811/29/2021C+程序设计 教师:39Program with Several FunctionsMain functionSquare

27、 functionCube function11/29/2021C+程序设计 教师:40Function Callna function call temporarily transfers control to the called functions code nwhen the functions code has finished executing, control is transferred back to the calling block 11/29/2021C+程序设计 教师:41FunctionName = ( Argument List )The argument li

28、st is a way for functions to communicate with each other by passing information.The argument list can contain 0, 1, or more arguments, separated by commas, depending on the function. Function Call SyntaxTwo Kinds of FunctionsAlways returns a single value to its caller and is called from within an ex

29、pression.Never returns a value to its caller, and is called as a separate statement. Value-Returning Void11/29/2021C+程序设计 教师:43A void function call stands alone#include using namespace std;void DisplayMessage ( int n ) ; / declares functionint main( ) DisplayMessage( 15 ) ; /function call cout “Good

30、 Bye“ endl ; return 0 ;11/29/2021C+程序设计 教师:44A void function does NOT return a value/ header and body herevoid DisplayMessage ( int n ) cout “I have liked math for “ n “ years” endl ;11/29/2021C+程序设计 教师:45Shortest C+ Programint main ( ) return 0;type of returned valuename of functionWhat is in a hea

31、ding? int main ( )type of returned valuename of functionsays no parameters11/29/2021C+程序设计 教师:47What is in a block?0 or more statements here11/29/2021C+程序设计 教师:48Every C+ function has 2 partsint main ( )heading body block return 0;11/29/2021C+程序设计 教师:49More About Functionsnit is not considered good

32、practice for the body block of function main to be long nfunction calls are used to do tasks11/29/2021C+程序设计 教师:50Where are functions? located in librariesOR written by programmers11/29/2021C+程序设计 教师:51HEADER 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

33、) sqrt(100.0) 10.0Book P84 log(x) log(2.0) .693147/log e (X) e = 2.71828183 sqrt(x) sqrt(2.0) 1.41421 abs(i) abs(-6) 611/29/2021C+程序设计 教师:52Write C+ Expressions forThe square root of b2 - 4ac sqrt ( b * b - 4.0 * a * c )The square root of the average of myAge and yourAgesqrt ( ( myAge + yourAge ) /

34、2 )11/29/2021C+程序设计 教师:53nIntegers and StringsnFloating-Point Numbers11/29/2021C+程序设计 教师:54n“set width” to control how many character positions the next data item should occupy when it is output. Can for numbers and strings and char data.ncout setw(fieldwidth) dataitem nThe dataitem to be output is

35、printed right-justified.nIf fieldwidth is not large enough for the dataitem, then it automatically expands to make room for all of the outputs.nSetting the fieldwidth is a one-time action.11/29/2021C+程序设计 教师:55n int ans = 33 , num = 7132;n cout setw(4) ansn setw(5) numn setw(4) Hi;n bb33b7132bbHi11/

36、29/2021C+程序设计 教师:56nDecimal point occupies one position.nBy default, large floating values are printed in scientific (E) notation. e.g. 123456789.5 1.234567E+08 nManipulator fixed can be used to force all subsequent output to appear in decimal form ( for a whole number, a decimal point does not be p

37、rinted ). n e.g. cout fixed 123456789.5 ; 123456789.5 nManipulator showpoint can be used to force all subsequent output to print a decimal point ,even for whole numbers.nManipulator setprecision(number) can be used to control the number of decimal places in all subsequent output. Last printed digit

38、is rounded off.11/29/2021C+程序设计 教师:57n float x = 310.0 , y= 4.827 ;n cout fixed n setw(10) n setprecision(2) n x ;n bbbb310.0011/29/2021C+程序设计 教师:58What is exact output?#include / for setw( ) and setprecision( )#include using namespace std;int main ( ) float myNumber = 123.4587 ; cout fixed showpoin

39、t ; / use decimal format / print decimal points cout “Number is ” setprecision ( 3 ) myNumber endl ; return 0 ;11/29/2021C+程序设计 教师:59OUTPUT Number is 123.459value is rounded if necessary to be displayed with exactly 3 places after the decimal point 11/29/2021C+程序设计 教师:60 float x = 312.0 ; float y =

40、4.827 ; cout fixed showpoint ; OUTPUT 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 More Examplesx312.0y4.82711/29/2021C+程序设计 教师:61HEADER MANIPULATOR ARGUMENT EFFECT FILE TYPE showpoint none d

41、isplays 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 11/29/2021C+程序设计 教师:62n string operations :n output , assignment , concatenation(+)n Additional:n length , n size

42、 , n find , n substr11/29/2021C+程序设计 教师:63length Functionnfunction length returns an unsigned integer value that equals the number of characters currently in the string nfunction size returns the same value as function length nyou must use dot notation in the call to function length or size 11/29/20

43、21C+程序设计 教师:64 e.g. string myName=simon; cout myName.length( ); 5 string:size_type len; len = myName.length( ) ;11/29/2021C+程序设计 教师:65find Functionnfunction find returns an unsigned integer value that is the beginning position for the first occurrence of a particular substring within the string nthe

44、 substring argument can be a string constant, a string expression, or a char value nif the substring was not found, function find returns the special value string:npos 11/29/2021C+程序设计 教师:66n string phrase = The dog and the cat;n string word = dog;n string:size_type position;n position = phrase.find

45、(the) / 12n position = phrase.find(rat) / string:nposn cout phrase.find(o); / 5n position = phrase.find(word) / 4n position = phrase.find(The +word) / 011/29/2021C+程序设计 教师:67substr Functionnfunction substr returns a particular substring of a string nthe first argument is an unsigned integer that spe

46、cifies a starting position within the string nthe second argument is an unsigned integer that specifies the length of the desired substring npositions of characters within a string are numbered starting from 011/29/2021C+程序设计 教师:68n string fullName n = Jonathan Alexander peterson ;n string name ;n s

47、tring:size_type startPos;n startPos = fullName.find(peterson) n / 19n name = Mr. + fullName.substr(startPos,8) n / Mr. peterson 11/29/2021C+程序设计 教师:69What is exact output?#include #include / for functions length, find, substrusing namespace std;int main ( ) string stateName = “Mississippi” ; cout st

48、ateName.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 ;11/29/2021C+程序设计 教师:70What is exact output?#include #include / for functions length, find, substrusing namespace std;int main

49、( ) 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 ;11/29/2021C+程序设计 教师:71

50、True/FalsenIn C+, the modulus operator (%) requires integer operands. 11/29/2021C+程序设计 教师:72nTrue11/29/2021C+程序设计 教师:73True/FalsenExecution of the statementnsomeInt = 3 * int(someFloat);ndoes not change the contents of the variable someFloat in memory.11/29/2021C+程序设计 教师:74nTrue11/29/2021C+程序设计 教师:7

51、5True/FalsenAssuming x and y are variables of type float, the expressionnsqrt(fabs(3.8 * x + 9.4 * y)nis a valid use of the sqrt and fabs library functions.11/29/2021C+程序设计 教师:76nTrue11/29/2021C+程序设计 教师:77True/FalsenThe setw manipulator is used only for formatting numeric values and strings, not char data.11/29/2021C+程序设计 教师:78nFalse11/29/2021C+程序设计 教师:79True/FalsenIf myString is a string variable and the

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论