C程序设计基础 英文版 课件全套 0.Lecture Introduction、Chapter1 Introducing C-Chapter 10 LinkedList_第1页
C程序设计基础 英文版 课件全套 0.Lecture Introduction、Chapter1 Introducing C-Chapter 10 LinkedList_第2页
C程序设计基础 英文版 课件全套 0.Lecture Introduction、Chapter1 Introducing C-Chapter 10 LinkedList_第3页
C程序设计基础 英文版 课件全套 0.Lecture Introduction、Chapter1 Introducing C-Chapter 10 LinkedList_第4页
C程序设计基础 英文版 课件全套 0.Lecture Introduction、Chapter1 Introducing C-Chapter 10 LinkedList_第5页
已阅读5页,还剩656页未读 继续免费阅读

下载本文档

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

文档简介

IntroductiontoProgramminginCPrograminginCTheoryCourseTextbookC程序设计基础(英文版)TextbookDepartment2MOOC(Chinese)3(Chinese)/course/NPU1-1457957182ClickthegreenbuttontojointhecourseMOOC(Chinese)45(English)/en/mooc/course/NPU1-1457957182MOOC(English)UsethisEnglishlinktologinifyoudon’thaveaChinesecellphone6IfyouhaveaGOOGLEaccountorGMAIL,thenchooseyouraccountEnteryourpassword.

Itmayaskyoutotypeinyourphonenumberafterthis.Round89Watchthevideos10Doyourhomeworks1112Askquestions13Changeyourusername1415YourIDorname16Xuetangonline/course/nwpu0809fu042313intl/5913023?channel=learn_titlepersonalprofile:Ucansetyournamehere.CollaborationandCheatingPolicyYouarewelcometodiscussassignmentswithotherstudents,providedthatallworkturnedinmustbeyourown.Cheatingwillnotbetolerated.19WhydoweneedC?ProgramminginCisabasiccourse.WecanlearnhowtowriteandrunaprogramItalsoisabasicforotherprogramminglanguage,suchasjava,C++etc.Cprogramminglanguagewasdesignedonearlyof1970,butisstillverypopularintheworld.20Whyweneedit?PopularityofLanguagesinTIOBEIndex21Courserequirement--KnowledgeMasterCdatatypesandexpression,canwritedifferentkindsofexpressioninC.Master3basiclogicalcontrolflow,canuse

these3basiclogicalcontrolflowtodesignprograms.Mastercommonfunctions,includingfunction

design,usageandparameters.

MasterCprogramstructureandsimplealgorithm.22Courserequirement-SkillsMasterhowtoreadandanalyzeCprogramMasterhowtodesignandwriteCprogram.MasterhowtodebugandrunCprogram.MastertheuseofanIDE(integrateddevelopmentenvironment)Understanderrorandwarningmessageandknowhowtodealwiththem.23TheEnd24Chapter1IntroducingCOutlinesChapter1IntroducingC1.1WhyProgrammingisImportant1.2WhyShouldWeLearnC1.3HistoryofC1.4StrengthsandWeaknessesofC1.5HowDoWeLearnC261.1WhyProgrammingisImportant?BeusedtoCommunicateLanguage+ProgrammingCprogrammingLanguageisawidelyusedhighlevelcomputerlanguage.27Whatisit?ProgramminginCWriteprogramsMakecomputerworkforus.28WhyShouldWeLearnC?IsCtheonlyprogramminglanguage?52’’29WhyShouldWeLearnC?1+1indifferentlanguage30#include<stdio.h>intmain(){printf("%d\n",1+1);return0;}2.1WritingaSimpleProgramCompilingandLinkingBeforeaprogramcanbeexecuted,threestepsareusuallynecessary:Preprocessing.Thepreprocessorobeyscommandsthatbeginwith#(knownasdirectives)Compiling.Acompilerthentranslatestheprogramintomachineinstructions(objectcode).Linking.Alinker

combinestheobjectcodeproducedbythecompilerwithanyadditionalcodesneededtoyield

acompleteexecutableprogram.312.1WritingaSimpleProgramTheGCCCompilerGCCisoneofthemostpopularCcompilers.GCCissuppliedwithLinuxbutisavailableformanyotherplatformsaswell.322.1WritingaSimpleProgramIntegratedDevelopmentEnvironmentsAnintegrateddevelopmentenvironment(IDE)isasoftwarepackagethatmakesitpossibletoedit,compile,link,execute,anddebugaprogramwithoutleavingtheenvironment.33Howdoesitwork?WriteaprogramwithIDE(IntegratedDevelopmentEnvironment)Talk(xxx.corxxx.cpp)Compiletheprogramtoanexecutablefile–Translate(xxx.exe)Runtheexecutablefileoncomputer--Communicate341.3HistoryofCOriginsofCCisaby-productofUNIX,developedatBellLaboratoriesbyKenThompson,DennisRitchie,andothers.KenThompson

designedasmalllanguagenamedB,basedonBCPL.By1971,DennisRitchiebegantodevelopanextendedversionofB.HecalledhislanguageNB(“NewB”)atfirst.AsthelanguagebegantodivergemorefromB,hechangeditsnametoC.Thelanguagewasstableenoughby1973thatUNIXcouldberewritteninC.351.3HistoryofCStandardizationofCgrammarK&RCDescribedinKernighanandRitchie,TheCProgrammingLanguage(1978)DefactostandardC89/C90ANSIstandardX3.159-1989(completedin1988;formallyapprovedinDecember1989)InternationalstandardISO/IEC9899:1990C99InternationalstandardISO/IEC9899:1999IncorporateschangesfromAmendment1(1995)361.3HistoryofCC-BasedLanguagesChasahugeinfluenceonmodern-dayprogramminglanguages.C++includesallthefeaturesofC,butaddsclassesandotherfeaturestosupportobject-orientedprogramming.JavaisbasedonC++andthereforeinheritsmanyCfeatures.C#isamorerecentlanguagederivedfromC++andJava.371.4StrengthsandWeaknessesofCStrengthsofCEasytocomprehendEfficiency:Cprogramcanrunquicklyandinlimitedamountsofmemory.CprogramsexecutemorequicklythanJavaandPythondo.Power:C’slargecollectionofdatatypesandoperatorshelpmakeitapowerfullanguage.

Portability:NottiedtoanyoneOperatingsystemormachineFlexibility:CimposesveryfewrestrictionsontheuseofitsfeaturesStandard

library:OneofC’sgreatstrengthsisitsstandardlibrary,whichcontainshundredsoffunctionsforinput/output,stringhandling,storageallocationandotherusefuloperations.381.2StrengthsandWeaknessesofCWeaknessesofCLackofobject-orientedprogrammingconceptsProgrammingskillsrequiredtolearn,sinceCProgramscanbeerror-prone.Programscanbedifficulttounderstand.Programscanbedifficulttomodify.LargeprogramswritteninCcanbehardtochangeiftheyhaven’tbeendesignedwithmaintenanceinmind.NotefficientascomparedtoPython.ThesyntaxofPythoniseasierAbsenceoftheconceptofnamespaceWithoutnamespaces,wecan’tdeclaretwofactors,likevariables,withthesamename.391.5Howtolearnit?PracticeisthemagicwordtolearnCKnowledge—learnthegrammar,keywordofC

programminglanguageSkill—learnhowtowrite,compileandrunC

program40Whenyoudon’tPRACTICECODEBLOCKSTheplacetowritethecode--codeblocksWheretowritethecode--codeblocksDownloadcodeblocksfromHowtouseit42WheretowriteyourprogramCodeBlocks

1.Goto:/downloads2.Click“Downloadthebinaryrelease”3.

Pleaseselectasetuppackagedependingonyourplatform:

E.g.WeuseWINDOWS:

3.Pleaseselectasetuppackagedependingonyourplatform:E.g.WeuseWINDOWS:

Pleaseselect“codeblocks-20.03minGW-setup.exe”。ClickDownloadfrom"FossHUB"

or"S"(Theyarethesame).(IfyoucannotinstallCODEBLOCKS,thendownload“codeblocks-20.03mingw-nosetup.zip”.Youdon'thavetoinstallit,justdownloaditthenyoucanuseit.)

4.Afteryoudownloadthefiles,clickitandsetupCode::Blocks.Note:Code::Blockswillbeinstalledinthedefaultfolder“C:\ProgramFiles\CodeBlocks”.Youshouldchangetoanotherfolder.TheruleistoavoidusingSPACEorChinesecharactersintheinstallationpath.However,between“Program”and“Files”,thereisaspace.So,youshoulduseadifferentfolder.Click“Browse..."tochangethefolderyouinstallitin,E.g.Ichangetoc:\mysoftwareYoucaninstallitdirectlyattherootdirectoryofdiskCordiskD,etc.Youcanalsoinstallitinotherplaces.Forexample,youcancreateanewfoldercalled“mysoftware”onyourdiskDandinstallCode::Blocksinthisnewfolder.Click“Browse...”tochangethefolderyouwanttoinstallitin.Forexample,wecanchangeitto“C:\mysoftware\CodeBlocks”Nowyoucanusecoldclocks.

Ifyouinstallandunsetupitmanytimes,youmaymeetsomeerrorslike"Can'tfindtheGNUGCCCompiler".PleaseseemyAnnouncement”Can'tfindacompiler“474849Typethe

name

of

yourproject

as

you

like

,c101,c102….e.g.Then

choosethe

Folder

tocreate

yourproject

in

by

clicking

thisbutton505115223Ifu

want

open

your

code

again11xcode56Mac

OS1.

Install

XCODEfromtheAppstore.2.

OpenXCODEthen

clickCreate

anew

XCODEproject572. ChooseCommand

LineTool

then

clicknext58•3.

type

thenameofyourproject59week1ex16061• 6.1622• 6.1632OnlineCompilerhttps://www.onlinegdb.com/online_c_compiler#1234TheEnd67Chapter2DataTypesandExpressionsOutlineChapter2DataTypesandExpressions2.1TheGeneralFormofaSimpleProgram2.2CharacterSetandKeywords2.3DataTypes2.4VariablesandConstants2.5OperatorsandExpressions69IntegratedDevelopmentEnvironmentsCode::Blocks702.1TheGeneralFormofaSimpleProgramNOTE:•Crequiresasemicolon(;)attheendofeverystatement.•statement.printfisastandardCfunction--calledfrommain.•Statementsshouldbeenclosedinbraces.•“\n”signifiesnewline.Formattedoutput--morelater.•Casesensitive,printfandPrintfaredifferent.•Linenumbercanbeshowninaneditor,itisnotthecontentofprogram.712.1TheGeneralFormofaSimpleProgram2.2TheGeneralFormofaSimpleProgramSimpleCprogramshavetheformwiththreeparts

directives

intmain()

{

statements

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

#include<stdio.h>stdio.h

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

providedaspartoftheCimplementation.74XXXXXX(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)752.2TheGeneralFormofaSimpleProgramStatements:Astatementisacommandtobeexecutedwhentheprogramruns.Crequiresthateachstatementendwithasemicolon(;)Helloworldusesonlytwokindsofstatements.Oneisthereturn

statement;theotheristhefunctioncall.Askingafunctiontoperformitsassignedtaskisknownascallingthefunction.main()callsprintf

todisplayastring:762.2TheGeneralFormofaSimpleProgramPrintingStringsTheprintf

functiondisplaysastring—charactersenclosedindoublequotationmarks(””).\n

(thenew-linecharacter)

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

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

/*Thisisthefirstlineofthecomment

Thisisthesecondlineofthecomment

*/

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

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

Examplesofillegalidentifiers:

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

jobjoBjObjOBJobJoBJObJOB862.3DataTypes87DataTypesvshotelrooms88A

bit

storesjusta0or1.

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

Byte

=8bitsTypesthesizeoftheemptybox/roomEveryvariablemusthaveatype.eg.

int

float、double

andchar.sizeMLXLS

storedata3312.3or99999999999‘a’Avariableoftypefloat

(shortforfloating-point)、double

canstoremuchlargernumbersthananint

variable.Also,afloat/double

variablecanstorenumberswithdigitsafterthedecimalpoint,like379.125.89Rangeandsizetype[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.无符号的整型数,其二进制的最左边一位也看成是数字的一部分。922.3.1IntegerTypesSignedandUnsignedIntegersBydefault,integervariablesinCaresigned—theleftmostbitisreservedforthesign.Totellthecompilerthatavariablehasnosignbit,declareittobeunsigned.C通常默认整型变量都是有符号的。(可以用来存储负数)如果要声明数据是无符号的,int前面要加上unsigned932.3.1IntegerTypesC’sintegertypecomesindifferentsizes.intintegerisusually32bits,butmaybe16bitsonolderCPUs.Longintegersmayhavemorebitsthanordinaryintegers;shortintegersmayhavefewerbits.Int型变量一般占4个字节32位二进制的存储空间。不同的CPU会有差异。942.3.1IntegerTypesTheCstandardrequiresthatshort

int,int,andlong

intmusteachcoveracertainminimumrangeofvalues.intmustnotbeshorterthanshort

int,andlong

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

short

int

unsigned

short

int

int

unsigned

int

long

int unsigned

long

intthewordintcanbedropped(long

intcanbeabbreviatedtojustlong).

Int可以省略。比如longint可以省略成long962.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存储范围表示了该类型的变量能存放的最大和最小的数。不同的机器上范围是不同的。972.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).982.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。两者的不同在于后者存储空间大,大约双倍精度。992.3.3CharacterTypeschargender;CharacterSetsToday’smostpopularcharactersetisASCII(AmericanStandardCodeforInformationInterchange),a7-bitcodecapableofrepresenting128characters.Ctreatscharactersassmallintegers.Thecharacter'a'hasthevalue97'A'hasthevalue65;'0'hasthevalue48‘1'hasthevalue49.

Characterconstantsactuallyhaveint

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

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

intheight,length,width,volume;

floatprofit,loss;

doublevolume;

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

beforetheyareused.

intmain()

{

intspam;//declarations定义

spam=15;//statements使用return0;

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

往变量里面存放数据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.104AssignmentAnint

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;???105AssignmentAssignmentOnceavariablehasbeenassignedavalue,itcanbeusedtohelpcomputethevalueofanothervariable:height=8;length=12;width=10;volume=height*length*width;/*volumeisnow960*/Therightsideofanassignmentcanbeaformula(orexpression,inCterminology).106107AssignmentInitialization(初始化)定义变量的同时赋初值Theinitialvalueofavariablemaybeincludedinitsdeclaration:

intheight=8;

Thevalue8issaidtobeaninitializer.

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

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

canbeusedtodisplaythecurrentvalueofavariable.conversionspecification格式说明符:beginwith%

%d

isaplaceholderindicatingwherethevalueofi

istobefilledin.

ddisplayanintegerindecimalform.i=3;printf(“Ihave%dcats\n",i);108Classexercise3:introduceyourfamilyCreateanewprojectnamed“ex03”introduceyourfamilyoryourpet.Thefilenamedoesn’tmatter,butdon’tusespace.1092.4.2ConstantsIntegerConstants整型常量,整数Constantsarenumbersthatappearinthetextofaprogram.Callowsintegerconstantstobewrittenindecimal(base10十进制),65octal(base8八进制),0101orhexadecimal(base16十六进制).0x411102.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.111IntegerConstantsDecimalconstantscontaindigitsbetween0and9,butmustnotbeginwithazero:十进制整型常量

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

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

0xf0xff0x7fffThelettersinahexadecimalconstantmaybeeitherupperorlowercase:

0xff0xfF0xFf0xFF0Xff0XfF0XFf0XFF112IntegerConstantsThetypeofadecimalintegerconstantisnormallyint.Toforcethecompilertotreataconstantasalonginteger,justfollowitwiththeletterL(orl):

15L

0377L

0x7fffLToindicatethataconstantisunsigned,puttheletterU(oru)afterit:

15U

0377U

0x7fffULandUmaybeusedincombination:

0xffffffffUL

TheorderoftheLandUdoesn’tmatter,nordoestheircase.十进制整数比如15会被默认为int型,如果想强制编译器把该数认为long型或者无符号整型。就要在数字后面加L或者U.(L,U可以小写)113IntegerConstantsinC99InC99,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.114ReadingandWritingIntegers八、十六、无符号数输入输出格式符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*/115ReadingandWritingIntegers十、八、十六、无符号数输入输出格式符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.116FloatingConstants实型常量(小数)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后必须为整数117TheremustbeanumberbeforeandafterE,andthenumberafterEmustbeaninteger注意:E前必须有数字,E后必须为整数118FloatingConstantsBydefault,floatingconstantsarestoredasdouble-precisionnumbers.Toindicatethatonlysingleprecision(float)isdesired,puttheletterF(orf)attheendoftheconstant(forexample,57.0F).Toindicatethataconstantshouldbestoredinlong

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

小数比如57.0会被默认为double类型的常量,如果要强制编译器把它看成float类型。就在后面加f。119ReadingandWritingFloating-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.120CharacterconstantsCharacterSetsAvariableoftypecharcanbeassignedanysinglecharacter: charch1,ch2,ch3,ch4;

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

areenc

温馨提示

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

评论

0/150

提交评论