C程序设计基础 英文版 课件 Chapter 2 Data Types and Expressions_第1页
C程序设计基础 英文版 课件 Chapter 2 Data Types and Expressions_第2页
C程序设计基础 英文版 课件 Chapter 2 Data Types and Expressions_第3页
C程序设计基础 英文版 课件 Chapter 2 Data Types and Expressions_第4页
C程序设计基础 英文版 课件 Chapter 2 Data Types and Expressions_第5页
已阅读5页,还剩105页未读 继续免费阅读

下载本文档

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

文档简介

Chapter2DataTypesandExpressionsFangWangOutlineChapter2DataTypesandExpressions2.1TheGeneralFormofaSimpleProgram2.2CharacterSetandKeywords2.3DataTypes2.4VariablesandConstants2.5OperatorsandExpressions2IntegratedDevelopmentEnvironmentsCode::Blocks32.1TheGeneralFormofaSimpleProgramNOTE:•Crequiresasemicolon(;)attheendofeverystatement.•statement.printfisastandardCfunction--calledfrommain.•Statementsshouldbeenclosedinbraces.•“\n”signifiesnewline.Formattedoutput--morelater.•Casesensitive,printfandPrintfaredifferent.•Linenumbercanbeshowninaneditor,itisnotthecontentofprogram.42.1TheGeneralFormofaSimpleProgram2.2TheGeneralFormofaSimpleProgramSimpleCprogramshavetheformwiththreeparts

directives

intmain()

{

statements

}EventhesimplestCprogramsrelyonthreekeylanguagefeatures:DirectivesFunctionsStatements52.2TheGeneralFormofaSimpleProgramDirectivesBeforeaCprogramiscompiled,itisfirsteditedbyapreprocessor.Commandsintendedforthepreprocessorarecalleddirectives.Example:

#include<stdio.h>stdio.h

isaheadercontaininginformationaboutC’sstandardI/Olibrary.Directivesalwaysbeginwitha#character.there’snosemicolonorotherspecialmarkerattheend.62.2TheGeneralFormofaSimpleProgramFunctionsAfunctionisaseriesofstatementsthathavebeengroupedtogetherandgivenaname.Afunctionisusuallydesignedtoperformaspecifictask.Libraryfunctionsare

providedaspartoftheCimplementation.7XXXXXX(XXX)

{

statements

}intmain()

{

statements

}2.2TheGeneralFormofaSimpleProgramThemainFunction

isspecialEveryCprogrammusthaveoneandonlyonemainfunctionsomewhere.main

isspecial:itgetscalledautomaticallywhentheprogramisexecuted.Thewordintjustbeforemainindicatesthemainfunctionreturnsanintegervalue.main

returnsacode;thevalue0indicatesnormalprogramtermination.Ifthere’snoreturn

statementattheendofthemain

function,manycompilerswillproduceawarningmessage.Thewordvoidinparentheses()indicatesthatmainhasnoarguments.(Youdon'thavetowritetheword“void”,justleaveitblank)82.2TheGeneralFormofaSimpleProgramStatements:Astatementisacommandtobeexecutedwhentheprogramruns.Crequiresthateachstatementendwithasemicolon(;)Helloworldusesonlytwokindsofstatements.Oneisthereturn

statement;theotheristhefunctioncall.Askingafunctiontoperformitsassignedtaskisknownascallingthefunction.main()callsprintf

todisplayastring:92.2TheGeneralFormofaSimpleProgramPrintingStringsTheprintf

functiondisplaysastring—charactersenclosedindoublequotationmarks(””).\n

(thenew-linecharacter)

10In-classassignment1:introduceyourselfCreateanewprojectnamed“ex01”Edityour“helloworld”anddisplay3statements:1.yournameandwhereareyoufrom2.Introduceyourcountry3.SaysomethingtoChina

Thefilenamedoesn’tmatter,butdon’tusespace.1112CommentsAcommentbeginswith/*andendwith*/.

/*Thisisthefirstlineofthecomment

Thisisthesecondlineofthecomment

*/

Commentscanalsobewritteninthefollowingway: //Thisisacomment1.CharacterLinesbetween/*and*/areacomment.2.Commentsexplainwhattheprogramdoes.3.Commentsareignoredbythecompiler.13In-classassignment2:commentsAddsomecommentsto“introduceyourself”

142.1.2TheBasicStepstoWriteaSimpleProgramWecanconsideranotherprogramthatinvolvesaddingtwonumbers,denotedasaandb15162.2CharacterSetandKeywordsAcharactersetisasetofalphabets,digits,andsomespecialcharactersthatarevalidintheClanguage.(1)AlphabetsUppercase:ABCDEFGHIJKLMNOPQRSTUVWXYZLowercase:abcdefghijklmnopqrstuvwxyz(2)Digits0123456789(3)SpecialCharacters<>._();$:%[]#?'&{}"^!*/|-\~+172.2.2Keywords182.2.3Identifiers---------NAMESNamesforvariables,functions….arecalledidentifiers.Anidentifiermaycontainletters,digits,andunderscores,butmustbeginwithaletterorunderscore: times10get_next_char

Examplesofillegalidentifiers:

10timesget-next-charCiscase-sensitive:itdistinguishesbetweenupper-caseandlower-caselettersinidentifiers.Forexample,thefollowingidentifiersarealldifferent:

jobjoBjObjOBJobJoBJObJOB192.3DataTypes20DataTypesvshotelrooms21A

bit

storesjusta0or1.

Inthecomputerit'sall0'sand1’s.Group8bitstogethertomake1byte.Onebyte=collectionof8bits.1

Byte

=8bitsTypes------thesizeoftheemptybox/roomEveryvariablemusthaveatype.eg.

int

float、double

andchar.sizeMLXLS

storedata3312.3or99999999999‘a’Avariableoftypefloat

(shortforfloating-point)、double

canstoremuchlargernumbersthananint

variable.Also,afloat/double

variablecanstorenumberswithdigitsafterthedecimalpoint,like379.125.22Rangeandsizetype[signed]intunsigned[int][signed]short[int]unsignedshort[int][signed]long[int]unsignedlong[int][signed]charunsignedcharfloatdoublelongdoubleSize(Byte)44224411488/12Range-2147483648~+2147483647

~0~4294967295

~-32768~+32767

~0~65535

~-2147483648~+2147483647

~0~4294967295

~-128~+127

~0~255

~3.4×10−381.7×10−308precision3.4×10381.7×103081.2×104932716191.2×10−4932/CProgrammingLanguageSomebasicdatatypesTypecharshortintlongfloatdoubleDescribeAcharacterofthelocalcharactersetshortintegerintegerlongintegersingle-precisionfloatingpointdouble-precisionfloatingpointCProgrammingLanguage522.3.1IntegerTypesTheintegertypes,aredividedintotwocategories:signedandunsigned.整型分有符号整型和无符号整型Theleftmostbitofasignedinteger(knownasthesignbit)is0ifthenumberispositiveorzero,1ifit’snegative.有符号的整型数,其二进制的最左边一位是符号位。0正1负Anintegerwithnosignbit(theleftmostbitisconsideredpartofthenumber’smagnitude)issaidtobeunsigned.无符号的整型数,其二进制的最左边一位也看成是数字的一部分。252.3.1IntegerTypesSignedandUnsignedIntegersBydefault,integervariablesinCaresigned—theleftmostbitisreservedforthesign.Totellthecompilerthatavariablehasnosignbit,declareittobeunsigned.C通常默认整型变量都是有符号的。(可以用来存储负数)如果要声明数据是无符号的,int前面要加上unsigned262.3.1IntegerTypesC’sintegertypecomesindifferentsizes.intintegerisusually32bits,butmaybe16bitsonolderCPUs.Longintegersmayhavemorebitsthanordinaryintegers;shortintegersmayhavefewerbits.Int型变量一般占4个字节32位二进制的存储空间。不同的CPU会有差异。272.3.1IntegerTypesTheCstandardrequiresthatshort

int,int,andlong

intmusteachcoveracertainminimumrangeofvalues.intmustnotbeshorterthanshort

int,andlong

intmustnotbeshorterthanint.通常他们所占的存储空间是short<=int<=long282.3.1IntegerTypesOnlysixcombinationsproducedifferenttypes:

short

int

unsigned

short

int

int

unsigned

int

long

int unsigned

long

intthewordintcanbedropped(long

intcanbeabbreviatedtojustlong).

Int可以省略。比如longint可以省略成long292.3.1IntegerTypesTherangeofvaluesrepresentedbyeachofthesixintegertypesvariesfromonemachinetoanother.Typicalrangesona64-bitmachine: Type SmallestValue LargestValue short

int –32,768 32,767 unsigned

short

int 0 65,535 int –2,147,483,648 2,147,483,647 unsigned

int 0 4,294,967,295 long

int –263 263–1 unsigned

long

int 0

264–1存储范围表示了该类型的变量能存放的最大和最小的数。不同的机器上范围是不同的。302.3.1IntegerTypesIntegerTypesinC99C99providestwoadditionalstandardintegertypes,long

long

intandunsigned

long

long

int.Bothlong

longtypesarerequiredtobeatleast64bitswide.Therangeoflong

long

intvaluesistypically–263(–9,223,372,036,854,775,808)to263–1(9,223,372,036,854,775,807).Therangeofunsigned

long

long

int

valuesisusually0to264–1(18,446,744,073,709,551,615).312.3.2FloatingTypes实型----浮点数(存储小数)Cprovidesthreefloatingtypes

Type SmallestPositiveValue LargestValue Precision

float 1.17549

10–38 3.40282

1038 6digits

double 2.22507

10–308 1.79769

10308 15digitsfloat Single-precisionfloating-point单精度浮点数doubledouble-precisionfloating-point双精度浮点数long

doubleExtended-precisionfloating-pointlong

doubleisrarelyused.实型变量一般用来存储带小数的数。计算机中通常以浮动小数点的形式来存储,所以实型也叫做浮点数。实型主要分两种,float和double。两者的不同在于后者存储空间大,大约双倍精度。322.3.3CharacterTypeschargender;CharacterSetsToday’smostpopularcharactersetisASCII(AmericanStandardCodeforInformationInterchange),a7-bitcodecapableofrepresenting128characters.Ctreatscharactersassmallintegers.Thecharacter'a'hasthevalue97'A'hasthevalue65;'0'hasthevalue48‘1'hasthevalue49.

Characterconstantsactuallyhaveint

typeratherthanchartype.332.4VariablesandConstantsVariable变量--------emptybox/roomMostprogramsneedawaytostoredatatemporarilyduringprogramexecution.Thesestoragelocationsarecalledvariables.34Variablenamevariable2.4VariablesandConstantsDeclarations定义变量-------分配相应的存储空间Todeclareavariable,wefirstspecifythetypeofthevariable,thenitsname.

类型变量名,变量名……;

intheight,length,width,volume;

floatprofit,loss;

doublevolume;

charch;作用:在内存中,为变量分配相应的存储空间,以便后面用来存放数据。35Declarations------checkinathotelVariablesmustbedeclared

beforetheyareused.

intmain()

{

intspam;//declarations定义

spam=15;//statements使用return0;

}变量一定要先定义(分配存储空间)后使用。36spam15AssignmentAssignment赋值

------往变量里面存放数据Avariablecanbegivenavaluebymeansofassignment:inth;

h=8;Thenumber8issaidtobeaconstant(常量)

. intspam;

spam=15;//youstoredthevalue15insidethevariablespam spam=3;Butwhenyouenterspam=3,thevalue15isoverwritten(thatis,replaced)withthevalue3.Theoldvalueinspamisforgotten.Aconstantassignedtoafloat/double

variableusuallycontainsadecimalpoint:

profit=2150.48;It’sbesttoappendtheletterftoafloating-pointconstantifitisassignedtoafloat

variable:

profit=2150.48f;Failingtoincludethe

f

maycauseawarningfromthecompiler.37AssignmentAnint

variableisnormallyassignedavalueoftypeint,adoublevariableisnormallyassignedavalueoftypedouble.intd;d=33;floatx;doublez;x=178.111;z=1899.111;charc1;c1=‘a’;通常:整数赋给整型变量(int),小数赋给实型变量(float,double)字符赋给字符型变量(char)Mixingtypes(suchasassigninganintvaluetoafloatvariableorassigningafloatvaluetoanintvariable)ispossiblebutnotalwayssafe.intd;d=33.6;???38AssignmentAssignmentOnceavariablehasbeenassignedavalue,itcanbeusedtohelpcomputethevalueofanothervariable:height=8;length=12;width=10;volume=height*length*width;/*volumeisnow960*/Therightsideofanassignmentcanbeaformula(orexpression,inCterminology).3940AssignmentInitialization(初始化)定义变量的同时赋初值Theinitialvalueofavariablemaybeincludedinitsdeclaration:

intheight=8;

Thevalue8issaidtobeaninitializer.

intheight=8,length=12,width=10;Eachvariablerequiresitsowninitializer.

intheight,length,width=10; /*initializesonlywidth*/40AssignmentPrintingtheValueofaVariable输出变量的值printf

canbeusedtodisplaythecurrentvalueofavariable.conversionspecification格式说明符:beginwith%

%d

isaplaceholderindicatingwherethevalueofi

istobefilledin.

ddisplayanintegerindecimalform.i=3;printf(“Ihave%dcats\n",i);41Classexercise3:introduceyourfamilyCreateanewprojectnamed“ex03”introduceyourfamilyoryourpet.Thefilenamedoesn’tmatter,butdon’tusespace.422.4.2ConstantsIntegerConstants整型常量,整数Constantsarenumbersthatappearinthetextofaprogram.Callowsintegerconstantstobewrittenindecimal(base10十进制),65octal(base8八进制),0101orhexadecimal(base16十六进制).0x41432.4.1IntegerTypesOctalandHexadecimalNumbers八、十六进制Octalnumbersuseonlythedigits0through7.Eachpositioninanoctalnumberrepresentsapowerof8.Theoctalnumber237representsthedecimalnumber

2×82+3×81+7×80=128+24+7=159.Ahexadecimal(orhex)numberiswrittenusingthedigits0through9plusthelettersAthroughF,whichstandfor10through15,respectively.Thehexnumber1AFhasthedecimalvalue1×162+10×161+15×160=256+160+15=431.44IntegerConstantsDecimalconstantscontaindigitsbetween0and9,butmustnotbeginwithazero:十进制整型常量

1525532767Octalconstantscontainonlydigitsbetween0and7,andmustbeginwithazero:八进制整型常量用0开头

0170377077777Hexadecimalconstantscontaindigitsbetween0and9andlettersbetweenaandf,andalwaysbeginwith0x:十六进制整型常量用0x开头

0xf0xff0x7fffThelettersinahexadecimalconstantmaybeeitherupperorlowercase:

0xff0xfF0xFf0xFF0Xff0XfF0XFf0XFF45IntegerConstantsThetypeofadecimalintegerconstantisnormallyint.Toforcethecompilertotreataconstantasalonginteger,justfollowitwiththeletterL(orl):

15L

0377L

0x7fffLToindicatethataconstantisunsigned,puttheletterU(oru)afterit:

15U

0377U

0x7fffULandUmaybeusedincombination:

0xffffffffUL

TheorderoftheLandUdoesn’tmatter,nordoestheircase.十进制整数比如15会被默认为int型,如果想强制编译器把该数认为long型或者无符号整型。就要在数字后面加L或者U.(L,U可以小写)46IntegerConstantsinC99InC99,integerconstantsthatendwitheitherLL

orll(thecaseofthetwolettersmustmatch)havetypelong

long

int.AddingtheletterU(oru)beforeoraftertheLLorlldenotesaconstantoftypeunsigned

long

long

int.C99’sgeneralrulesfordeterminingthetypeofanintegerconstantareabitdifferentfromthoseinC89.Thetypeofadecimalconstantwithnosuffix(U,u,L,l,LL,orll)isthe“smallest”ofthetypesint,long

int,orlong

long

intthatcanrepresentthevalueofthatconstant.47ReadingandWritingIntegers八、十六、无符号数输入输出格式符Readingandwritingunsigned,short,andlongintegersrequiresnewconversionspecifiers.Whenreadingorwritinganunsignedinteger,usetheletteru,o,x

insteadofdintheconversionspecification.

%u%o%x

unsignedintu;

scanf("%u",&u);/*readsuinbase10*/ printf("%u",u);/*writesuinbase10*/ scanf("%o",&u);/*readsuinbase8*/ printf("%o",u);/*writesuinbase8*/ scanf("%x",&u);/*readsuinbase16*/ printf("%x",u);/*writesuinbase16*/48ReadingandWritingIntegers十、八、十六、无符号数输入输出格式符Whenreadingorwritingashortinteger,puttheletterhinfrontofd,o,u,orx:%hd%ho%hu%hx

shorts;

scanf("%hd",&s); printf("%hd",s);Whenreadingorwritingalonginteger,puttheletterl

infrontofd,o,u,orx.%ld%lo%lu%lxWhenreadingorwritingalong

long

integer(C99only),putthelettersllinfrontofd,o,u,orx.49FloatingConstants实型常量(小数)Floatingconstantscanbewritteninavarietyofways.Validwaysofwritingthenumber57.0:

57.057.57.0e057E05.7e15.7e+1 .57e2570.e-1Afloatingconstantmustcontainadecimalpointand/oranexponent;theexponentindicatesthepowerof10bywhichthenumberistobescaled.Ifanexponentispresent,itmustbeprecededbytheletterE

(ore).Anoptional+or-signmayappearaftertheE(ore).TheremustbeanumberbeforeandafterE,andthenumberafterEmustbeaninteger小数就是实型常量。可以写成小数或者科学记数法两种形式。注意:E前后必须有数字,E后必须为整数50TheremustbeanumberbeforeandafterE,andthenumberafterEmustbeaninteger注意:E前必须有数字,E后必须为整数51FloatingConstantsBydefault,floatingconstantsarestoredasdouble-precisionnumbers.Toindicatethatonlysingleprecision(float)isdesired,puttheletterF(orf)attheendoftheconstant(forexample,57.0F).Toindicatethataconstantshouldbestoredinlong

doubleformat,puttheletterL(orl)attheend(57.0L).

小数比如57.0会被默认为double类型的常量,如果要强制编译器把它看成float类型。就在后面加f。52ReadingandWritingFloating-PointNumbers%e,%f,and%gareusedforreadingandwritingsingle-precisionfloating-pointnumbers.Whenreadingavalueoftypedouble,puttheletterlinfrontofe,f,org:

floatd; scanf("%f",&d);printf("%f",d); doubled; scanf("%lf",&d);printf("%f",d);Note:Uselonlyinascanfformatstring,notaprintfstring.53CharacterconstantsCharacterSetsAvariableoftypecharcanbeassignedanysinglecharacter: charch1,ch2,ch3,ch4;

ch1='a';/*lower-casea*/97 ch2='A';/*upper-caseA*/65 ch3='0';/*zero*/48 ch4='';/*space*/32Noticethatcharacterconstants

areenclosedinsinglequotes,notdoublequotes.一般形式的字符常量:用单引号括起来的单个字符54OperationsonCharactersCtreatscharactersassmallintegers.Thecharacter'a'hasthevalue97'A'hasthevalue65;'0'hasthevalue48''hasthevalue32.

Characterconstantsactuallyhaveint

typeratherthanchartype.ch=‘a’;这句话实际上等价于ch=97;因为实际上存放在变量ch里面的是a的ASCII值97.555656Charactersinmemory字符数据在内存中存放的是其ASCII值。charc1,c2;c1=‘a’;c2=‘b’

;c1c297980110000101100010在用户眼里是字母a,在内存中实际存储的是97OperationsonCharactersWhenacharacterappearsinacomputation,Cusesitsintegervalue. charch; inti;

i='a';/*iisnow97*/ ch=65;/*chisnow'A'*/ ch=ch+1;/*chisnow'B'*/ ch++;/*chisnow'C'*/C会把字符常量处理成整数,也就是他的ASCII值。所以,在一定程度上char和int是可以通用的。57EscapeSequencesAcharacterconstantisusuallyonecharacterenclosedinsinglequotes.However,certainspecialcharacters—includingthenew-linecharacter—can’tbewritteninthisway,becausethey’reinvisible(nonprinting)orbecausetheycan’tbeenteredfromthekeyboard.Escapesequencesprovideawaytorepresentthesecharacters.Therearetwokindsofescapesequences:characterescapesandnumericescapes.58EscapeSequencesAcompletelistofcharacterescapes:

Name EscapeSequence Alert(bell) \a

Backspace \b Formfeed \f

Newline \n Carriagereturn \r

Horizontaltab \t Verticaltab \v

Backslash \\

Questionmark \? Singlequote \' Doublequote \"59Characterescapesarehandy,buttheydon’texistforallnonprintingASCIIcharacters.Characterescapesarealsouselessforrepresentingcharactersbeyondthebasic128ASCIIcharacters.EscapeSequencesNumericescapescanrepresentanycharacter.Anumericescapeforaparticularcharacterusesthecharacter’soctalorhexadecimalvalue.octalescapesequencehexadecimalescapesequence60EscapeSequencesAnoctalescapesequenceconsistsofthe\characterfollowedbyanoctalnumberwithatmostthreedigits,suchas\33or\101.用字符的8进制ASCII码值代表字符;Ahexadecimalescapesequenceconsistsof\xfollowedbyahexadecimalnumber,suchas\x41or\x1B.用字符的16进制ASCII码值代表字符;Thexmustbeinlowercase,butthehexdigitscanbeupperorlowercase.61‘A’‘\101’‘\X41’62例:整型量、字符量互相赋值和通用格式符

charc;inti;c=97;i=’b’;printf(”%c,%d\n”,c,c);printf(”%c,%d\n”,i,i);

a,97 b,98Outlines2.5.1ArithmeticOperators算术运算符2.5.2AssignmentOperators赋值运算符2.5.3IncrementandDecrementOperators自增自减运算符2.5.4ExpressionEvaluation表达式2.5.5ExpressionStatement表达式语句63OperatorsExpressionsarebuiltfromvariables,constants,andoperators.Eachexpressionhasitsowntypeandvalue.Chasarichcollectionofoperators,includingarithmeticoperatorsrelationaloperatorslogicaloperatorsassignmentoperatorsincrementanddecrementoperators andmanyothers642.5.1ArithmeticOperatorsUnaryArithmeticOperators一元算术运算符Therearealsotwounaryarithmeticoperators:

+ unaryplus

- unaryminusTheunaryoperatorsrequireoneoperand:

i=+1; j=-i;652.5.1ArithmeticOperatorsOperatorAssociativity(操作符结合律,有左结合和右结合两种)Associativitycomesintoplaywhenanexpressioncontainstwoormoreoperatorswithequalprecedence.Anoperatorissaidtobeleftassociative(左结合)

ifitgroupsfromlefttoright.Thebinaryarithmeticoperators(*,/,%,+,and-)areallleftassociative,so

i

-

j

kisequivalentto(i

-

j)

-

k

i

*

j

/

kisequivalentto(i

*

j)

/

kAnoperatorisrightassociative(右结合)

ifitgroupsfromrighttoleft.Theunaryarithmeticoperators(+and-)arebothrightassociative,so

-

+

iisequivalentto-(+i)当表达式中有多个运算符时,先看优先级,如优先级相同,则看结合律,左结合就从左向右算,右结合就从右向左算。只有少数运算符是右结合的。662.5.1ArithmeticOperatorsOperatorPrecedence(操作符优先级)先乘除后加减Doesi

+

j

*

k

mean“addiandj,thenmultiplytheresultbyk”or“multiplyjandk,thenaddi”?Onesolutiontothisproblemistoaddparentheses,writingeither(i

+

j)

*

k

ori

+

(j

*

k).Iftheparenthesesareomitted,Cusesoperatorprecedencerulestodeterminethemeaningoftheexpression.672.5.1ArithmeticOperatorsOperatorPrecedence

(操作符优先级)Thearithmeticoperatorshavethefollowingrelativeprecedence:

Highest: +

-(unary)正负号

*

/

% Lowest: +

-(binary)

Examples:

i

+

j

*

k

isequivalenttoi

+

(j

*

k)

-i

*

-j

isequivalentto(-i)

*

(-j)

+i

+

j

/

k

isequivalentto(+i)

+

(j

/

k)682.5.1ArithmeticOperatorsBinaryArithmeticOperators混合运算Binaryarithmeticoperators(withtheexceptionof%remainder)alloweitherintegerorfloating-pointoperands,withmixingallowed.Whenint

anddouble

operandsaremixed,theresulthastypedouble.

9+2.5hasthevalue11.5,and6.7

/

2hasthevalue3.35.

整型数据和实型数据混合运算,结果为实型

整型和整型运算,结果为整型

实型和实型运算,结果为实型692.5.1ArithmeticOperatorsBinaryArithmeticOperators二元算术运算符Cprovidesfivebinaryarithmeticoperators:

+ addition

- subtraction

* multiplication

/ division

% remainder(整数相除取余数)RemainderoperatorThevalueofi

%

j

istheremainderwheniisdividedbyj.

iandjmustbeintegers整数

10

%

3hasthevalue1,and10

%

5hasthevalue0.702.5.1ArithmeticOperatorsBinaryArithmeticOperatorsThe/and%operatorsrequirespecialcare:Whenbothoperandsareintegers,/“truncates”theresult.Thevalueof1

/

2

is0,not0.5.Thevalueof1.0/

2

is0.5.The%operatorrequiresintegeroperands;InC99,thevalueofa

%

bhasthesamesignasa.--5%3-2--5%-3-2712.5.2AssignmentOperators赋值运算符Simpleassignment:usedforstoringavalueintoavariableCompoundassignment:usedforupdatingavaluealreadystoredinavariable722.5.2AssignmentOperators赋值运算符SimpleAssignment:

v

=

e变量=常数、变量、表达式….Theeffectoftheassignmentv

=

e

istocalculatetheexpressioneandcopyitsvalueintov.ecanbeaconstant,avariable,oramorecomplicatedexpression:

x=111;/*xisnow111*/ y=x;/*yisnow111*/ z=5*x+y;/*zisnow666*/732.5.2AssignmentOperatorsLvalues左值Theassignmentoperatorrequiresanlvalueasitsleftoperand.Anlvaluerepresentsanobjectstoredincomputermemory,notaconstantortheresultofacomputation.Variablesarelvalues;Variables=…..等号的左边只能是变量742.5.2AssignmentOperatorsIfvandedon’thavethesametype,thenthevalueofeisconvertedtothetypeofvastheassignmenttakesplace:

inti; doublef;

i=72.99;/*iisnow72*/ f=136;/*fisnow136.0*/SideEffectsAnoperatorsthatmodifiesoneofitsoperandsissaidtohaveasideeffect

.Thesimpleassignmentoperatorhasasideeffect:itmodifiesitsleftoperand.752.5.2AssignmentOperatorsSideEffectsSinceassignmentisanoperator,severalassignmentscanbechainedtogether:

a=b=c=0;The=

operatorisrightassociative,sothisassignmentisequivalentto

a=(b=(c=0));Watchoutforunexpectedresultsinchainedassignmentsasaresultoftypeconversion:

inta; doubleb;

b=a=123.3;iisassignedthevalue33,thenfisassigned33.0(not33.3).762.5.2AssignmentOperatorsSimpleAssignmentInmanyprogramminglanguages,assignmentisastatement;inC,however,assignmentisanoperator,justlike+.v=eisanexpression.Thevalueofanassignmentv

=

e

isthevalueofvaftertheassignment.赋值表达式的值就是左边变量的值。772.5.2AssignmentOperatorsSideEffectsAnassignmentoftheformv

=

e

isallowedwhereveravalueoftypevwouldbepermitted:

i=1; k=1+(j=i); printf("%d%d%d\n",i,j,k); /*prints112*/“赋值表达式的值就是左边变量的值。782.5.2AssignmentOperatorsLvaluesSincetheassignmentoperatorrequiresanlvalueasitsleftoperand,it’sillegaltoputanyotherkindofexpressionontheleftsideofanassignmentexpression:

12=i;/***WRONG***/ i+j=0;/***WRONG***

温馨提示

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

评论

0/150

提交评论