c理论程序设计_第1页
c理论程序设计_第2页
c理论程序设计_第3页
c理论程序设计_第4页
c理论程序设计_第5页
已阅读5页,还剩88页未读 继续免费阅读

下载本文档

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

文档简介

1、7/15/2022C+程序设计 教师:鲍钰1C+程序设计(3)教师:鲍钰 7/15/2022C+程序设计 教师:鲍钰2Chapter 3. Numeric Types, Expressions, and OutputC+ built-in data types are organized into simple types, structured types, and address types. 7/15/2022C+程序设计 教师:鲍钰3C+ Data Typesstructuredarray struct union class addresspointer referencesimpl

2、e integral enumchar short int long boolfloatingfloat double long double7/15/2022C+程序设计 教师:鲍钰4C+ Simple Data Typessimple typesintegralfloating char short int long bool enum float double long doubleunsigned7/15/2022C+程序设计 教师:鲍钰5Standard Data Types in C+Integral Typesrepresent whole numbers and their n

3、egativesdeclared as int, short, or longFloating Typesrepresent real numbers with a decimal pointdeclared as float, or doubleCharacter Typerepresents single charactersdeclared as char7/15/2022C+程序设计 教师:鲍钰6Samples of C+ Data Valuesint sample values 4578 -45780float sample values95.27495.2659521E-3-95E

4、-195.213E2char sample values B d 4? *7/15/2022C+程序设计 教师:鲍钰7 About Integral TypesThe 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. e.g. sizeof(int) is int types

5、size in byte. sizeof(char)=sizeof(short)= sizeof(int)= sizeof(long)In a 32-bit machine : char : 1 byte -128,127 short : 2 byte -32768,32767 int : 4 byte -2147483648, 2147483647 long : 4 byte -2147483648, 2147483647 Most compilers dont give error message when integer overflow occurs. e.g. INT_MAX +1

6、INT_MIN7/15/2022C+程序设计 教师:鲍钰8int type literalsDecimal 22 16 1 498 0 4600 -378 -912Octal 022 015Hexadecimal 0 xFF 0X107/15/2022C+程序设计 教师:鲍钰9Scientific Notation 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.02.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.000277/15/2022C+程序设计 教师:鲍钰10More About Floating Point Valuesf

7、loating 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 alternatively, floating point values can have an exponent, as in scientific notation-the numb

8、er preceding the letter EEXAMPLES 1.84E1 5E2 8E-1 -.127358E37/15/2022C+程序设计 教师:鲍钰11Arithmetic Operators P73Unary : +(plus) -(minus)Binary: + - * /(integral,floating-point ) %(modulus)(integral only) -3%2 /-17.0/2.0 / 3.5 double/double double7/2 / 3 int/int int7/15/2022C+程序设计 教师:鲍钰12Division Operator

9、 P75the result of the division operator depends on the type of its operands if one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type Examples11 / 4 has value 211.0 / 4.0 has value 2.7511 / 4.0 has value 2.757/15/2022C+程序设计 教师:鲍钰

10、13Main returns 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 wateri

11、nt main ( ) float avgTemp ; / Holds the result of averaging / FREEZE_PT and BOIL_PT7/15/2022C+程序设计 教师:鲍钰14Function 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

12、 is “ ; cout avgTemp “ degrees.” endl ; return 0 ;7/15/2022C+程序设计 教师:鲍钰15Modulus Operatorthe modulus operator % can only be used with integer type operands and always has an integer type result its result is the integer type remainder of an integer division EXAMPLE11 % 4 has value 3 because)411R = 2

13、7/15/2022C+程序设计 教师:鲍钰16More C+ Operators8int age;age = 8;age = age + 1; age9age7/15/2022C+程序设计 教师:鲍钰17PREFIX FORMIncrement Operator8int age;age = 8;+age; age9age7/15/2022C+程序设计 教师:鲍钰18POSTFIX FORM Increment Operator8int age;age = 8;age+; age9age7/15/2022C+程序设计 教师:鲍钰19Decrement Operator100int dogs;do

14、gs = 100;dogs-; dogs99dogs7/15/2022C+程序设计 教师:鲍钰20Which Form to Usewhen 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 EITHER7/15/2022C+程序设计 教师:鲍钰

15、21BUT.when the 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 . . .7/15/2022C+程序设计 教师:鲍钰22Increment and Decrement Operators Difference between suffix and prefix:Suffix: expression(num+) value

16、is original value of the operand. Prefix: expression(+num) value is new value of the operand. e.g. int num=10; cout num+ num;/ 10 10cout num+; cout num;/ 11 12int num=10; cout +num num;/ 11 10cout +num; cout b? 1:27/15/2022C+程序设计 教师:鲍钰25Some C+ OperatorsPrecedence OperatorDescription Higher ( )Funct

17、ion call +Positive -Negative *Multiplication / Division %Modulus (remainder) +Addition -SubtractionLower = Assignment7/15/2022C+程序设计 教师:鲍钰26Precedencehigher Precedence determines which operator is applied first in an expression having several operators p684 Appendix B7/15/2022C+程序设计 教师:鲍钰27Associati

18、vityleft to right Associativity means that in an expression having 2 operators with the same priority, the left operator is applied first in C+ the binary operators * , / , % , + , - are all left associative expression 9 - 5 - 1 means ( 9 - 5 ) - 14 - 1 37/15/2022C+程序设计 教师:鲍钰287 * 10 - 5 % 3 * 4 + 9

19、means (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 Expression7/15/2022C+程序设计 教师:鲍钰29Parenthesesparentheses can be used to change the usual orderparts in ( ) are evaluated firstevaluate (7 * (10 - 5)

20、% 3) * 4 + 9 ( 7 * 5 % 3 ) * 4 + 9 ( 35 % 3 ) * 4 + 9 2 * 4 + 9 8 + 9 177/15/2022C+程序设计 教师:鲍钰30Type Coercion and Type CastingType Coercion - The implicit (automatic) conversion of a value from one type to another.Type Casting - The explicit conversion of a value from one type to another.Conversions

21、may take place in assignments, initializations and mixed types mode expressions .7/15/2022C+程序设计 教师:鲍钰31Variable = Expressionfirst, Expression on right is evaluatedthen the resulting value is stored in the memory location of Variable on left NOTE: An automatic type coercion occurs after evaluation b

22、ut before the value is stored if the types differ for Expression and VariableAssignment Operator Syntax7/15/2022C+程序设计 教师:鲍钰32What value is stored?float a;float b;a = 8.5;b = 9.37;a = b;abab8.59.37?7/15/2022C+程序设计 教师:鲍钰33What is stored? float someFloat; someFloat someFloat = 12;/ causes implicit typ

23、e conversionsomeFloat12.07/15/2022C+程序设计 教师:鲍钰34What is stored? int someInt; someInt someInt = 4.8;/ causes implicit type conversionsomeInt47/15/2022C+程序设计 教师:鲍钰35Examples Type casting: form1: typename(expression) form2: (typename)expression Convert from type of expression to type denoted by typenam

24、e someFloat = float(3*someInt +2); / int float someFloat = (float)(3*someInt +2); / int float someInt = int(5.2 / someFloat anotherFloat); / double int someInt = int(someFloat +0.5) ; / double int /rounding off floating-point number7/15/2022C+程序设计 教师:鲍钰36Type Casting is Explicit Conversion of Typein

25、t(4.8) has value4float(5)has value5.0float(7/4)has value1.0float(7) / float(4) has value1.757/15/2022C+程序设计 教师:鲍钰37Some Expressionsint age;EXAMPLEVALUEage = 8 8- age- 85 + 8135 / 8 06.0 / 5.01.2float ( 4 / 8 )0.0float ( 4 ) / 80.57/15/2022C+程序设计 教师:鲍钰38Function Concept in Math f ( x ) = 5 x - 3When

26、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 functionParameter of functionFunction definition7/15/2022C+程序设计 教师:鲍钰39Function Calls and Library FunctionsValue

27、 Returning FunctionsLibrary FunctionsVoid Functions ProceduresP82-847/15/2022C+程序设计 教师:鲍钰40Program with Several FunctionsMain functionSquare functionCube function7/15/2022C+程序设计 教师:鲍钰41Function Calla function call temporarily transfers control to the called functions code when the functions code has

28、 finished executing, control is transferred back to the calling block 7/15/2022C+程序设计 教师:鲍钰42FunctionName = ( Argument List )The argument list 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, depe

29、nding on the function. Function Call SyntaxTwo Kinds of FunctionsAlways 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 Void7/15/2022C+程序设计 教师:鲍钰44A void function call stands alon

30、e#include using namespace std;void DisplayMessage ( int n ) ; / declares functionint main( ) DisplayMessage( 15 ) ; /function call cout “Good Bye“ endl ; return 0 ;7/15/2022C+程序设计 教师:鲍钰45A void function does NOT return a value/ header and body herevoid DisplayMessage ( int n ) cout “I have liked mat

31、h for “ n “ years” endl ;7/15/2022C+程序设计 教师:鲍钰46Shortest C+ Programint main ( ) return 0;type of returned valuename of functionWhat is in a heading? int main ( )type of returned valuename of functionsays no parameters7/15/2022C+程序设计 教师:鲍钰48What is in a block?0 or more statements here7/15/2022C+程序设计

32、教师:鲍钰49Every C+ function has 2 partsint main ( )heading body block return 0;7/15/2022C+程序设计 教师:鲍钰50More About Functionsit is not considered good practice for the body block of function main to be long function calls are used to do tasks7/15/2022C+程序设计 教师:鲍钰51Where are functions? located in libraries

33、OR written by programmers7/15/2022C+程序设计 教师:鲍钰52HEADER 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.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) 67/15/2022C+程序设计 教师:鲍钰53Write C+ Expr

34、essions 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 ) / 2 )7/15/2022C+程序设计 教师:鲍钰54Formatting the OutputIntegers and StringsFloating-Point Numbers7/15/2022C+程序设计 教师:鲍钰55setw Manipulator“set width” to control ho

35、w many character positions the next data item should occupy when it is output. Can for numbers and strings and char data.cout setw(fieldwidth) dataitem The dataitem to be output is printed right-justified.If fieldwidth is not large enough for the dataitem, then it automatically expands to make room

36、for all of the outputs.Setting the fieldwidth is a one-time action.7/15/2022C+程序设计 教师:鲍钰56Examples book p87 int ans = 33 , num = 7132; cout setw(4) ans setw(5) num setw(4) Hi; bb33b7132bbHi7/15/2022C+程序设计 教师:鲍钰57Floating-Point NumbersDecimal point occupies one position.By default, large floating val

37、ues are printed in scientific (E) notation. e.g. 123456789.5 1.234567E+08 Manipulator fixed can be used to force all subsequent output to appear in decimal form ( for a whole number, a decimal point does not be printed ). e.g. cout fixed 123456789.5 ; 123456789.5 Manipulator showpoint can be used to

38、 force all subsequent output to print a decimal point ,even for whole numbers.Manipulator setprecision(number) can be used to control the number of decimal places in all subsequent output. Last printed digit is rounded off.7/15/2022C+程序设计 教师:鲍钰58Examples book p89 float x = 310.0 , y= 4.827 ; cout fi

39、xed setw(10) setprecision(2) x ; bbbb310.007/15/2022C+程序设计 教师:鲍钰59What is exact output?#include / for setw( ) and setprecision( )#include using namespace std;int main ( ) float myNumber = 123.4587 ; cout fixed showpoint ; / use decimal format / print decimal points cout “Number is ” setprecision ( 3

40、 ) myNumber endl ; return 0 ;7/15/2022C+程序设计 教师:鲍钰60OUTPUT Number is 123.459value is rounded if necessary to be displayed with exactly 3 places after the decimal point 7/15/2022C+程序设计 教师:鲍钰61 float x = 312.0 ; float y = 4.827 ; cout fixed showpoint ; OUTPUT cout setprecision ( 2 ) setw ( 10 ) x endl

41、 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.8277/15/2022C+程序设计 教师:鲍钰62HEADER MANIPULATOR ARGUMENT EFFECT FILE TYPE showpoint none displays decimal point fixed none suppresses scientific notation setprecision(n)

42、 int sets precision to n digits setw(n) int sets fieldwidth to n positions endl none terminates output line 7/15/2022C+程序设计 教师:鲍钰63Additional string Operations string operations : output , assignment , concatenation(+) Additional: length , size , find , substr7/15/2022C+程序设计 教师:鲍钰64length Functionfu

43、nction 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 7/15/2022C+程序设计 教师:鲍钰65 e.g. string myName=simon; cout myName.length(

44、); 5 string:size_type len; len = myName.length( ) ;7/15/2022C+程序设计 教师:鲍钰66find Functionfunction 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 express

45、ion, or a char value if the substring was not found, function find returns the special value string:npos 7/15/2022C+程序设计 教师:鲍钰67Examples string phrase = The dog and the cat; string word = dog; string:size_type position; position = phrase.find(the) / 12 position = phrase.find(rat) / string:npos cout

46、phrase.find(o); / 5 position = phrase.find(word) / 4 position = phrase.find(The +word) / 07/15/2022C+程序设计 教师:鲍钰68substr Functionfunction substr returns a particular substring of a string the first argument is an unsigned integer that specifies a starting position within the string the second argumen

47、t is an unsigned integer that specifies the length of the desired substring positions of characters within a string are numbered starting from 07/15/2022C+程序设计 教师:鲍钰69Examples string fullName = Jonathan Alexander peterson ; string name ; string:size_type startPos; startPos = fullName.find(peterson)

48、/ 19 name = Mr. + fullName.substr(startPos,8) / Mr. peterson 7/15/2022C+程序设计 教师:鲍钰70What is exact output?#include #include / for functions length, find, substrusing namespace std;int main ( ) string stateName = “Mississippi” ; cout stateName.length( ) endl; cout stateName.find(“is”) endl; cout state

49、Name.substr( 0, 4 ) endl; cout stateName.substr( 4, 2 ) endl; cout stateName.substr( 9, 5 ) endl; return 0 ;7/15/2022C+程序设计 教师:鲍钰71What is exact output?#include #include / for functions length, find, substrusing namespace std;int main ( ) string stateName = “Mississippi” ; cout stateName.length( ) e

50、ndl; / 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 ;7/15/2022C+程序设计 教师:鲍钰72HomeworkP102-1035, 6, 167/15/2022C+程序设计 教师:鲍钰73Programming Exerc

51、isesP104-1052,6,7,10,127/15/2022C+程序设计 教师:鲍钰74True/FalseIn C+, the modulus operator (%) requires integer operands. 7/15/2022C+程序设计 教师:鲍钰75True7/15/2022C+程序设计 教师:鲍钰76True/FalseExecution of the statementsomeInt = 3 * int(someFloat);does not change the contents of the variable someFloat in memory.7/15/2022C+程序设计 教师:鲍钰77True7/15/2022C+程序设计 教师:鲍钰78True/FalseAssuming x and y are variables of type float, the expressionsqrt(fabs(3.8 * x + 9.4 *

温馨提示

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

评论

0/150

提交评论