C程序设计第二章基本数据类型及运算.ppt_第1页
C程序设计第二章基本数据类型及运算.ppt_第2页
C程序设计第二章基本数据类型及运算.ppt_第3页
C程序设计第二章基本数据类型及运算.ppt_第4页
C程序设计第二章基本数据类型及运算.ppt_第5页
已阅读5页,还剩78页未读 继续免费阅读

下载本文档

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

文档简介

1,C的基本数据类型及运算,信息对抗,电子工程学院,2,标识符,标识符就是给程序中的变量、常量、函数、数组、结构体以及文件所起的名字。1命名规则:()以字母或下划线开头,由字母、数字和下划线组成;()不能和系统关键字同名;()尽量不要用下划线开头;()一般对长度无规定;()大小写是不同的字母(大小写敏感)。,例:判断下列标识符号合法性sumSumM.D.JohndayDate3daysstudent_name#33lotus_1_2_3charab_above$123,M.D.John,3days,#33,char,$123,ab,3,标识符,好的命名习惯:()尽量做到见名知意;(sum,area)()变量名、函数名用小写,符号常量用大写;()在易混淆地方,尽量避免用易认错的字母;e.g.0(数字)(大写字母)o(小写字母)1(数字)I(I的大写字母)l(L的小写字母)(数字)(大写字母)z(小写字母),4,KeywordsandReservedIdentifiers,ISO/ANSICKeywordsautoenumrestrictunsignedbreakexternreturnvoidcasefloatshortvolatilecharforsignedwhileconstgotosizeof_Boolcontinueifstatic_Complexdefaultinlinestruct_Imaginarydointswitchdoublelongtypedefelseregisterunion,5,注意:1C语言区分大小写,2标识符的长度一般不超过32个字符,如:Price和price,系统会认为是两个不同的标识符。,具体情况视不同系统而定。,6,数据类型DataTypes,程序应包括两个方面的内容:数据的描述。操作步骤,即动作的描述。数据不仅是操作的对象,而且操作结果会改变数据的状况。计算机科学家沃思(NiklklausWirth)提出一个公式:数据结构十算法=程序程序算法十数据结构十程序设计方法十语言工具和环境C语言中,任何一个数据都必须属于一种类型,7,C语言对程序中要用到的每一个变量都要事先指定它的数据类型!,为什么要指定数据类型?,1不同类型的数据在内存中占据不同长度的存储区。2不同类型的数据取值范围不同。3不同类型的数据有不同的操作。,8,C语言数据类型,数据类型,基本类型,构造类型,指针类型,字符型char整型int实型float,double空类型void,枚举型enum数组(Array)结构体struct共用体union,9,基本数据类型,Void:1,函数不返回任何值2,同一类型指针,10,类型修饰符,除void类型以外,基本数据类型可以带各种修饰符作为前缀.右边四个修饰符可以用于字符型和整型的基本类型.Long还可以用于双精度实型.整型数缺省状态为signed和short.,11,基本类型和修饰符组合,12,数据类型的缺省等价形式,13,浮点数,在计算机中,定点数通常只用于表示整数或纯小数。而对于既有整数部分又有小数部分的数,由于其小数点的位置不固定,一般用浮点数表示,由两部分组成:尾数和2的幂,地址,0,内容,SEEEEEEE,EMMMMMMM,MMMMMMMM,MMMMMMMM,1,2,3,说明:S:符号位,1代表负,0代表正E:偏移127的幂,为阶码(即多少次方的意思)M:24位尾数保存在23位中,最高位为1省略,则:浮点数的值(符号)2(EEEEEEEE)-127尾数,14,例:浮点数0 xC10 x480 x000 x00的值二进制表示:11000001010010000000000000000000符号位S1,故为负数阶码(10000010)1271301273尾数1.100100000000000000000001.5625所以:其代表的值为-1231.5625-12.5,15,常量constants,Somedataarepresetbeforeaprogramisusedandkeeptheirvaluesunchangedthroughoutthelifeoftheprogram.Theseareconstants.(常量:具有固定的值,且不会被程序改变)数值常量整型常量,实型常量,双精度常量字符常量字符串常量符号常量,16,整型常量,整型常量即整常数。整常数可用以下三种形式表示:十进制整数。如123、-456、0。八进制整数。以0开头的数是八进制数。如0123表示八进制数123,即(123)8等于十进制数83。-011表示八进制数-11,即十进制数-9。十六进制整数。以0 x开头的数是进制数。如0 x123,代表16进制数123,即(123)161162163160=256323=291。-0 x12等于十进制数一18。,整型常量的类型根据其值所在范围确定其数据类型在整常量后加字母l或L,认为它是longint型常量,例12与12L,例30000为int型65536为longint型,17,实型常量,实数在语言中又称浮点数,实数有两种表示形式:1.小数形式。它由数字和小数点组成(注意必须有小数点)。0.123、.123、123.0、123.、0.0都是十进制数形式。2.指数形式。如123e3或123E3都代表123103但注意字母e(或E)之前必须有数字。且e后面指数必须为整数,如e3、2.1e3.5、e等都不是合法的指数形式。规范化(标准化)指数形式:在字母e(或E)之前的小数部分中,小数点左边应有一位(且只能有一位)非零的数字。,实型常量的类型默认double型在实型常量后加字母f或F,认为它是float型,18,定义:用单引号括起来的单个普通字符或转义字符.,字符常量的值:该字符的ASCII码值,如101-A012-n376-x61-a60-0483-(),例:A-101-x41-65,如A65,a97,048,n10,如aA?n101,转义字符:反斜线后面跟一个字符或一个代码值表示,例转义字符举例main()printf(101x42Cn);printf(Isay:Howareyou?n);printf(CProgramn);printf(TurboC);,运行结果:(屏幕显示)ABCIsay:”Howareyou?”CProgramTurboC,例main()printf(“Yb=n”);,运行结果:屏幕显示:=打印机输出:,字符常量,19,字符常量与字符串常量不同,定义:用双引号(“”)括起来的字符序列存储:每个字符串尾自动加一个0作为字符串结束标志,例:charch;ch=“A”;,字符串常量,20,举例,#includemain()printf(abctdenftgn);printf(abctderftgn);printf(htibbjkn);printf(htijkn);printf(h12345678ijkn);,21,ConstantsandtheCPreprocessor,Sometimesyouneedtouseaconstantinaprogram.Forexample,youcouldgivethecircumferenceofacircleasfollows:circumference=3.14159*diameter;Here,theconstant3.14159representstheworld-famousconstantpi().Touseaconstant,justtypeintheactualvalue,asintheexample.However,therearegoodreasonstouseasymbolicconstantinstead.Thatis,youcoulduseastatementsuchasthefollowingandhavethecomputersubstituteintheactualvaluelater:circumference=pi*diameter;,22,Whytouseasymbolicconstant?,First,anametellsyoumorethananumberdoes.Comparethefollowingtwostatements:owed=0.015*housevalue;owed=taxrate*housevalue;Ifyoureadthroughalongprogram,themeaningofthesecondversionisplainer.Also,supposeyouhaveusedaconstantinseveralplaces,anditbecomesnecessarytochangeitsvalue.Afterall,taxratesdochange.Thenyouonlyneedtoalterthedefinitionofthesymbolicconstant,ratherthanfindandchangeeveryoccurrenceoftheconstantintheprogram.,23,howsetupasymbolicconstant?,Onewayistodeclareavariableandsetitequaltothedesiredconstant.Youcouldwritethis:floattaxrate;taxrate=0.015;Thisprovidesasymbolicname,buttaxrateisavariable,soyourprogrammightchangeitsvalueaccidentally.Fortunately,Chasacouplebetterideas.,24,#defineNAMEvalue,Justaddalinelikethefollowingatthetopofthefilecontainingyourprogram:#defineTAXRATE0.015Whenyourprogramiscompiled,thevalue0.015willbesubstitutedeverywhereyouhaveusedTAXRATE.Thisiscalledacompiletimesubstitution.,25,符号常量SymbolicConstants,C语言允许将程序中的常量定义为一个标识符,称为符号常量。符号常量一般使用大写英文字母表示,以区别于一般用小写字母表示的变量。符号常量在使用前必须先定义,定义的形式是:#define是宏定义预处理命令,不是C语句例如:#definePI3.1415926#defineTRUE1#definrFALSE0#defineSTAR*这里定义PI、TRUE、FLASE、STAR为符号常量,其值分别为3.1415926,1,0,*。,26,compiletimesubstitution,27,examples,The#definestatementcanbeusedforcharacterandstringconstants,too.Justusesinglequotesfortheformeranddoublequotesforthelatter.Thefollowingexamplesarevalid:#defineBEEPa#defineTEET#defineESC033#defineOOPSNowyouhavedoneit!Rememberthateverythingfollowingthesymbolicnameissubstitutedforit.Dontmakethiscommonerror:/*thefollowingiswrong*/#defineTOES=20Ifyoudothis,TOESisreplacedby=20,notjust20.Inthatcase,astatementsuchasdigits=fingers+TOES;isconvertedtothefollowingmisrepresentation:digits=fingers+=20;,28,The#undefDirective,The#undefdirectivecancelsanearlier#definedefinition.Thatis,supposeyouhavethisdefinition:#defineLIMIT400Thenthedirective#undefLIMITremovesthatdefinition.Now,ifyoulike,youcanredefineLIMITsothatithasanewvalue.EvenifLIMITisnotdefinedinthefirstplace,itisstillvalidtoundefineit.,29,The#undefDirective,#definePI3.14159Main()#undefPI/*从此往后,PI不在代表3.14159*/F1(),30,带参数的宏定义,除了字符串的替换,还要进行参数替换。定义形式:#defineS(a,b)a*b.area=S(3,2);预处理后:area=3*2;注意:1,宏名和参数之间不能有空格2,注意括号的使用,保证运算次序。,31,TheconstModifier,C90addedasecondwaytocreatesymbolicconstantsusingtheconstkeywordtoconvertadeclarationforavariableintoadeclarationforaconstant:constintMONTHS=12;/MONTHSasymbolicconstantfor12ThismakesMONTHSintoaread-onlyvalue.Thatis,youcandisplayMONTHSanduseitincalculations,butyoucannotalterthevalueofMONTHS.,32,概念:其值可以改变的量变量名与变量值变量定义的一般格式:数据类型变量1,变量2,变量n;,变量初始化:定义时赋初值,例:inta,b,c;floatdata;,决定分配字节数和数的表示范围,合法标识符,例:inta=2,b,c=4;floatdata=3.67;charch=A;intx=1,y=1,z=1;intx=y=z=1;X,变量的使用:先定义,后使用,例1intstudent;stadent=19;/Undefinedsymbolstadentinfunctionmain,例2floata,b,c;c=a%b;/Illegaluseoffloatingpointinfunctionmain,变量定义位置:一般放在函数开头,变量Variables,33,占字节数随机器不同而不同,一般占一个机器字shortintlong可用sizeof(类型标识符)测量,实型变量float:占4字节,提供7位有效数字double:占8字节,提供1516位有效数字,字符型变量字符变量存放字符ASCII码char与int数据间可进行算术运算,例1:floata;a=111111.111;/*a=111111.1*/例2:doubleb;b=111111.111;/*b=111111.111*/,例a=D;/*a=68;*/x=A+5;/*x=65+5;*/s=!+G/*s=33+71;*/,没有字符串变量,用字符数组存放,整型变量,34,#definePRICE12.5main()intnum=3;floattotal;charch1,ch2=D;total=num*PRICE;ch1=ch2-A+a;printf(“total=%f,ch1=%cn”,total,ch1);,运行结果:total=37.500000,ch1=d,例子,35,EnumeratedTypes,declaresymbolicnamestorepresentintegerconstants.Byusingtheenumkeyword,youcancreateanewtypeandspecifythevaluesitmayhave.(Actually,enumconstantsaretypeint,thereforetheycanbeusedwhereveryouwoulduseanint.)Thepurposeofenumeratedtypesistoenhancethereadabilityofaprogram.Forexample,youcanmakethesedeclarations:enumspectrumred,orange,yellow,green,blue,violet;enumspectrumcolor;Theidentifierswithinthebracesenumeratethepossiblevaluesthataspectrumvariablecanhave.,establishesspectrumasatagname,makescoloravariableofthattype,36,Usage,Therefore,thepossiblevaluesforcolorarered,orange,yellow,andsoon.Then,youcanusestatementslikethefollowing:intc;color=blue;if(color=yellow).;for(color=red;color=!=)逻辑运算符:(!,a=b=c=d;,相当于:a=(b=(c=d);,45,ArithmeticOperators,+加法,正值。如:3+6,+3,减法,负值。如:64,5,乘法。如:38,/除法。如:8/5,%求余。如:7%4的值为3,46,基本算术运算符:+-*/%结合方向:从左向右优先级:-*/%-+-(2)(3)(4)说明:“-”可为单目运算符时,右结合性两整数相除,结果为整数%要求两侧均为整型数据,例5/2=-5/2.0=,例5%2=-5%2=1%10=5%1=5.5%2,算术运算符和表达式,2,-2.5,1,-1,1,0,(),47,DivisionOperator:integerdivision,两个整数相除结果为整数,如5/3的结果值为1,舍去小数部分。但是如果除数或被除数中有一个为负值,则舍入的方向是不固定的。例如,53在有的机器上得到结果1,有的机器则给出结果2。多数机器采取“向零取整”方法,即5/31,53=1,取整后向零靠拢。如果参加运算的两个数中有一个数为实数,则结果是double型,因为所有实数都按double型进行运算。,48,Thedivide.cProgram,/*divide.c-divisionswehaveknown*/#includeintmain(void)printf(integerdivision:5/4is%dn,5/4);printf(integerdivision:6/3is%dn,6/3);printf(integerdivision:7/4is%dn,7/4);printf(floatingdivision:7./4.is%1.2fn,7./4.);printf(mixeddivision:7./4is%1.2fn,7./4);return0;,integerdivision:5/4is1integerdivision:6/3is2integerdivision:7/4is1floatingdivision:7./4.is1.75mixeddivision:7./4is1.75,Noticehowintegerdivisiondoesnotroundtothenearestinteger,butalwaystruncates,thatis,discardstheentirefractionalpart.,49,ModulusOperator:%,usedinintegerarithmetic.givestheremainderthatresultswhentheintegertoitsleftisdividedbytheintegertoitsright.Forexample,13%5(readas13modulo5)hasthevalue3,because5goesinto13twice,witharemainderof3.Dontbothertryingtousethisoperatorwithfloating-pointnumbers.Itjustwontwork.Onecommonuseistohelpyoucontroltheflowofaprogram.,50,Whataboutnegativenumbers?,BeforeC99settledonthetruncatetowardzeroruleforintegerdivision,therewereacoupleofpossibilities.Butwiththeruleinplace,yougetanegativemodulusvalueifthefirstoperandisnegativeandapositivemodulusotherwise:11/5is2and11%5is111/-5is-2and11%-2is1-11/-5is2and-11%-5is-1-11/5is-2and-11%5is-1Ifyoursystemshowsdifferentbehavior,ithasntcaughtuptotheC99standard.Inanycase,thestandardsays,ineffect,thatifaandbareintegervalues,youcancalculatea%bbysubtracting(a/b)*bfroma.Forexample,youcanevaluate“-11%5”thisway:-11-(-11/5)*5=-11-(-2)*5=-11-(-10)=-1,51,IncrementandDecrementOperators:+and-,Theincrementoperatorperformsasimpletask;itincrements(increases)thevalueofitsoperandby1.Thisoperatorcomesintwovarieties.Thefirstvarietyhasthe+comebeforetheaffectedvariable;thisistheprefixmode.Thesecondvarietyhasthe+aftertheaffectedvariable;thisisthepostfixmode.Thetwomodesdifferwithregardtotheprecisetimethattheincrementingtakesplace.,52,自增、自减运算符(+and-),作用是使变量的值增1或减1,如:+i,-i(在使用i之前,先使i的值加(减)1)i+,i-(在使用i之后,使i的值加(减)l)+i和i+的作用相当于ii+1。但+i和i+不同之处在于+i是先执行i=i+1后,再使用i的值;而i+是先使用i的值后,再执行i=i+1。如果i的原值等于3,则:j+i;j的值为4j=i+;j的值为3,然后i变为4又如:i=3;printf(”d”,+i);输出“4”。若改为printf(”d”,i+);则输出“3”。,例j=3;k=+j;j=3;k=j+;j=3;printf(“%d”,+j);j=3;printf(“%d”,j+);a=3;b=5;c=(+a)*b;a=3;b=5;c=(a+)*b;,/k=4,j=4,/k=3,j=4,/4,/3,/c=20,a=4,/c=15,a=4,53,说明,+/-只能用于变量,不能用于常量或表达式,如5+或(a+b)+都是不合法的。因为5是常量,常量的值不能改变。(a+b)+也不可能实现,假如a+b的值为5,那么自增后得到的6放在什么地方呢?无变量可供存放+,-的结合方向是“自右至左”。运算符的结合方向为“自左而右”,是大家所熟知的。如果有-i+,i的左面是负号运算符,右面是自加运算符。如果i的原值等于3,若按左结合性,相当于(-i)+,而(-i)+是不合法的。对表达式不能进行自加自减运算。自增(减)运算符常用于循环语句中使循环变量自动加1。也用于指针变量,使指针指向下一个地址。,54,说明,+-结合方向:自右向左优先级:-+-*/%-+-(2)(3)(4),例-i+-(i+)i=3;printf(“%d”,-i+);/-3,例-i+i=3;printf(“%d”,-i+);,55,AssignmentOperator:=,InC,theequalsigndoesnotmeanequals.Rather,itisavalue-assigningoperator.Thestatementbmw=2002;assignsthevalue2002tothevariablenamedbmw.Thatis,theitemtotheleftofthe=signisthenameofavariable,andtheitemontherightisthevalueassignedtothevariable.The=symboliscalledtheassignmentoperator.Again,dontthinkofthelineassaying,bmwequals2002.Instead,readitasassignthevalue2002tothevariablebmw.Theactiongoesfromrighttoleftforthisoperator.,56,Thestatementi=i+1;.,i=i+1;Asmathematics,thisstatementmakesnosense.Ifyouadd1toafinitenumber,theresultisntequaltothenumberyoustartedwith,butasacomputerassignmentstatement,itisperfectlyreasonable.ItmeansFindthevalueofthevariablenamedi;tothatvalue,add1,andthenassignthisnewvaluetothevariablenamedi,57,Modifiablelvalue,Astatementsuchas2002=bmw;makesnosenseinC(indeed,isinvalid)because2002isjustaconstant.Youcantassignavaluetoaconstant;Whenyousitdownatthekeyboard,rememberthatitemtotheleftofthe=signmustbethenameofavariable.Actually,theleftsidemustrefertoastoragelocation.Thesimplestwayistousethenameofavariable,but,asyouwillseelater,apointercanbeusedtopointtoalocation.Moregenerally,Cusesthetermmodifiablelvaluetolabelthoseentitiestowhichyoucanassignvalues.,58,DataObjects,Lvalues,Rvalues,andOperands,Adataobjectisageneraltermforaregionofdatastoragethatcanbeusedtoholdvalues.Cusesthetermlvaluetomeananameorexpressionthatidentifiesaparticulardataobject.Thenameofavariableisanlvalue,soobjectreferstotheactualdatastorage,butlvalueisalabelusedtoidentify,orlocate,thatstorage.Notallobjectscanhavetheirvalueschanged,soCusesthetermmodifiablelvaluetoidentifyobjectswhosevaluecanbechanged.leftsideofanassignmentoperatorshouldbeamodifiablelvalue.LLeft,59,rvalue,referstoquantitiesthatcanbeassignedtomodifiablelvalues.Forinstance,considerthefollowingstatement:bmw=2002;Here,bmwisamodifiablelvalue,and2002isanrvalue.Asyouprobablyguessed,therinrvaluecomesfromright.Rvaluescanbeconstants,variables,oranyotherexpressionthatyieldsavalue.Aslongasyouarelearningthenamesofthings,thepropertermforwhatwehavecalledanitem(asintheitemtotheleftofthe=)isoperand.Operandsarewhatoperatorsoperateon.,60,tripleassignment,/*golf.c-golftournamentscorecard*/#includeintmain(void)intjane,tarzan,cheeta;cheeta=tarzan=jane=68;printf(cheetatarzanjanen);printf(Firstroundscore%4d%8d%8dn,cheeta,tarzan,jane);return0;,Theassignmentsaremaderighttoleft:Firstjanegetsthevalue68,andthentarzandoes,andfinallycheetadoes.Therefore,theoutputisasfollows:cheetatarzanjaneFirstroundscore686868,61,简单赋值运算符,符号:=格式:变量标识符=表达式作用:将一个数据(常量或表达式)赋给一个变量,例a=3;d=func();c=d+2;,62,复合赋值运算符,种类:+=-=*=/=%=a+b=3;,例floatf;inti;i=10;f=i;则f=10.0,例inti;i=2.56;/结果i=2;,例:a=b=c=5a=(b=5)a=5+(c=6)a=(b=4)+(c=6)a=(b=10)/(c=2),/表达式值为5,a,b,c值为5,/b=5;a=5,/表达式值11,c=6,a=11,/表达式值10,a=10,b=4,c=6,/表达式值5,a=5,b=10,c=2,说明(1):,64,复合赋值运算符,结合方向:自右向左优先级:14左侧必须是变量,不能是常量或表达式赋值转换规则:使赋值号右边表达式值自动转换成其左边变量的类型赋值表达式的值与变量值相等,且可嵌套,例:a=12;a+=a

温馨提示

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

评论

0/150

提交评论