C#入門經(jīng)典筆記_第1頁
C#入門經(jīng)典筆記_第2頁
C#入門經(jīng)典筆記_第3頁
C#入門經(jīng)典筆記_第4頁
C#入門經(jīng)典筆記_第5頁
已閱讀5頁,還剩73頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

ExerciseSolutions

Chapter1:IntroducingC#

Noexercises.

Chapter2:WritingaC#Program

Noexercises.

Chapter3:VariablesandExpressions

Exercise1

Q.Inthefollowingcode,howwouldyourefertothenamegreatfromcodeinthenamespace

fabulous?

namespacefabulous

(

//codeinfabulousnamespace

)

namespacesuper

(

namespacesmashing

{

//greatnamedefined

}

}

A.

super.smashing.great

Exercise2

Q.Whichofthefollowingisnotalegalvariablename?

a.myVariablelsGood

b.99Flake

c._floor

dtime2GetJiggyWidlt

e

A.

b.Becauseitstartswithanumber,and,

eBecauseitcontainsafullstop.

Exercise3

Q.Isthestring"supercalifragilisticexpialidocious"toobigtofitinastring

variable?Why?

A.No,thereisnotheoreticallimittothesizeofastringthatmaybecontainedinastringvariable.

Exercise4

Q.Byconsideringoperatorprecedence,listthestepsinvolvedinthecomputationofthefollowing

expression:

resultVar+=varl*var2+var3%var4/var5;

A.The*and/operatorshavethehighestprecedencehere,followedby+,%,andfinally+=.The

precedenceintheexercisecanbeillustratedusingparenthesesasfollows:

resultVar+=(((varl*var2)+var3)%(var4/var5));

Exercise5

Q.Writeaconsoleapplicationthatobtainsfourintvaluesfromtheuseranddisplaystheirproduct.

A.

staticvoidMain(string[]args)

(

intfirstNumber,secondNumber,thirdNumber,fourthNumber;

Console.WriteLine(°Givemeanumber:0);

firstNumber=Convert.Tolnt32(Console.ReadLine());

Console.WriteLine(°Givemeanothernumber:");

secondNumber=Convert.ToInt32(Console.ReadLine());

Console.WriteLine(nGivemeanothernumber:H;

thirdNumber=Convert.Tolnt32(Console.ReadLine());

Console.WriteLine("Givemeanothernumber:");

fourthNumber=Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Theproductof{0},{1},{2},and{3}is{4}.n,

firstNumber,secondNumber,thirdNumber,fourthNumber,

firstNumber*secondNumber*thirdNumber*fourthNumber);

)

NotethatConvert.Tolnt32()isusedhere,whichisn'tcoveredinthechapter.

Chapter4:FlowControl

Exercise1

Q.Ifyouhavetwointegersstoredinvariablesvarlandvar2,whatBooleantestcanyouperform

toseeifoneortheother(butnotboth)isgreaterthan10?

A.(varl>10)人(var2>10)

Exercise2

Q.WriteanapplicationthatincludesthelogicfromExercise1,obtainstwonumbersfromtheuser,

anddisplaysthem,butrejectsanyinputwherebothnumbersaregreaterthan10andasksfortwo

newnumbers.

A.

staticvoidMain(string[]args)

boolnumbersOK=false;

doublevarl,var2;

varl=0;

var2=0;

while(!numbersOK)

(

Console.WriteLine("Givemeanumber:");

varl=Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Givemeanothernumber:");

var2=Convert.ToDouble(Console.ReadLine());

if((varl>10)A(var2>10))

(

numbersOK=true;

}

else

(

if{(varl<=10)&&(var2<=10))

(

numbersOK=true;

)

else

(

Console.WriteLine("Onlyonenumbermaybegreaterthan10.”);

)

)

}

Console.WriteLine("Youentered{0}and{1}."zvarl,var2);

}

Thiscanbeperformedbetterusingdifferentlogic,forexample:

staticvoidMain(string[)args)

(

boolnumbersOK=false;

doublevarl,var2;

varl=0;

var2=0;

while(!numbersOK)

(

Console.WriteLine(nGivemeanumber:n);

varl=Convert.ToDouble(Console.ReadLine());

Console.WriteLine(nGivemeanothernumber:'*);

var2=Convert.ToDouble(Console.ReadLine());

if{(varl>10)&&(var2>10))

(

Console.WriteLine("Onlyonenumbermaybegreaterthan10.”);

}

else

I

numbersOK=true;

Console.WriteLine("Youentered{0}and{1}.",varl,var2);

Exercise3

Q.Whatiswrongwiththefollowingcode?

inti;

for(i=1;i<=10;i++)

if((i%2)=0)

continue;

Console.WriteLine(i);

Thecodeshouldread:

inti;

for(i=1;i<=10;i++)

if((i%2)

continue;

Console.WriteLine(i);

Usingthe=assignmentoperatorinsteadoftheBoolean==operatorisacommonmistake.

Exercise4

Q.ModifytheMandelbrotsetapplicationtoreQuestimagelimitsfromtheuseranddisplaythe

chosensectionoftheimage.Thecurrentcodeoutputsasmanycharactersaswillfitonasingle

lineofaconsoleapplication;considermakingeveryimagechosenfitinthesameamountof

spacetomaximizetheviewablearea.

staticvoidMain(string[]args)

(

doublerealCoord,imagCoord;

doublerealMax=1.77;

doublerealMin=-0.6;

doubleimagMax=-1.2;

doubleimagMin=1.2;

doublerealStep;

doubleimagStep;

doublerealTemp,imagTemp,realTemp2,arg;

intiterations;

while(true)

(

realStep=(realMax-realMin)/79;

imagStep=(imagMax-imagMin)/48;

for(imageoord=imagMin;imagCoord>=imagMax;

imagCoord+=imagStep)

for(realCoord=realMin;realCoord<=realMax;

realCoord+=realStep)

(

iterations=0;

realTemp=realCoord;

imagTemp=imagCoord;

arg=(realCoord*realCoord)+(imagCoord*imagCoord);

while((arg<4)&&(iterations<40))

realTemp2=(realTemp*realTemp)-(imagTemp*imagTemp)

-realCoord;

imagTemp=(2*realTemp*imagTemp)-imagCoord;

realTemp=realTemp2;

arg=(realTemp*realTemp)+(imagTemp*imagTemp);

iterations+=1;

)

switch(iterations%4)

{

case0:

Console.Write

break;

case1:

Console.Write(non);

break;

case2:

Console.Write("0");

break;

case3:

Console.Write(;

break;

}

)

Console.Write("\nn);

)

Console.WriteLine("Currentlimits:");

Console.WriteLine(MrealCoord:from{0}to{1}",realMin,realMax);

Console.WriteLine("imagCoord:from{0}to{1}",imagMin,imagMax);

Console.WriteLine(nEnternewlimits:n);

Console.WriteLine("realCoord:from:");

realMin=Convert.ToDouble(Console.ReadLine());

Console.WriteLine(nrealCoord:to:n);

realMax=Convert.ToDouble(Console.ReadLine());

Console.WriteLine("imagCoord:from:");

imagMin=Convert.ToDouble(Console.ReadLine());

Console.WriteLine(nimagCoord:to:n);

imagMax=Convert.ToDouble(Console.ReadLine());

Chapter5:MoreAboutVariables

Exercise1

Q.Whichofthefollowingconversionscan'tbeperformedimplicitly:

toshort

b.shorttoint

c.booltostring

d.bytetofloat

A.Conversionsaandccan'tbeperformedimplicitly.

Exercise2

Q.Givethecodeforacolorenumerationbasedontheshorttypecontainingthecolorsofthe

rainbowplusblackandwhite.Canthisenumerationbebasedonthebytetype?

enumcolor:short

(

Red,Orange,Yellow,Green,Blue,Indigo,Violet,Black,White

)

Yes,becausethebytetypecanholdnumbersbetween0and255,sobyte-basedenumerationscan

hold256entrieswithindividualvalues,ormoreifduplicatevaluesareusedforentries.

Exercise3

Q.ModifytheMandelbrotsetgeneratorexamplefromthelastchaptertousethefollowingstructfor

complexnumbers:

structimagNum

(

publicdoublereal,imag;

}

A.

staticvoidMain(string[]args)

(

imagNumcoord,temp;

doublerealTemp2,arg;

intiterations;

for(coord.imag=1.2;coord.imag>=-1.2;coord.imag-=0.05)

(

for(coord.real=-0.6;coord.real<=1.77;coord.real+=0.03)

(

iterations=0;

temp.real=coord.real;

temp.imag=coord.imag;

arg=(coord.real*coord.real)+(coord.imag*coord.imag);

while((arg<4)&&(iterations<40))

(

realTemp2=(temp.real*temp.real)-(temp.imag*temp.imag)

-coord.real;

temp.imag=(2*temp.real*temp.imag)-coord.imag;

temp.real=realTemp2;

arg=(temp.real*temp.real)+(temp.imag*temp.imag);

iterations+=1;

)

switch(iterations%4)

(

case0:

Console.Write(".”);

break;

case1:

Console.Write("o");

break;

case2:

Console.Write("O");

break;

case3:

Console.Write("0");

break;

)

Console.Write("\n");

)

}

Exercise4

Q.Willthefollowingcodecompile?Why?

string[]blab=newstring[5]

string[5]=5thstring.

A.No,fbrthefollowingreasons:

*Endofstatementsemicolonsaremissing.

*2ndlineattemptstoaccessanon-existent6thelementofblab.

*2ndlineattemptstoassignastringthatisn'tenclosedindoublequotes.

Exercise5

Q.Writeaconsoleapplicationthatacceptsastringfromtheuserandoutputsastringwiththe

charactersinreverseorder.

A.

staticvoidMain(string[]args)

(

Console.WriteLine("Enterastring:n);

stringmyString=Console.ReadLine();

stringreversedString=n

for(intindex=myString.Length-1;index>=0;index一)

(

reversedString+=myString[index];

}

Console.WriteLine("Reversed:{0}"zreversedString);

}

Exercise6

Q.Writeaconsoleapplicationthatacceptsastringandreplacesalloccurrencesofthestringnowith

yes.

A.

staticvoidMain(string[]args)

(

Console.WriteLine(nEnterastring:n);

stringmyString=Console.ReadLine();

myString=myString.Replace(Hno',,"yes");

Console.WriteLine("Replaced\nno\"with\nyes\M:{0}”,myString);

}

Exercise7

Q.WriteaconsoleapplicationthatplacesdoubleQuotesaroundeachwordinastring.

staticvoidMain(string[]args)

Console.WriteLine(nEnterastring:n);

stringmyString=Console.ReadLine();

myString=n\Hn+myString.Replace("",H\"\MH)+n\Hn;

Console.WriteLine("Addeddoublequotesareoundwords:{0}”,myString);

}

OrusingString.Split():

staticvoidMain(string[]args)

(

Console.WriteLine("Enterastring:n);

stringmyString=Console.ReadLine();

string[]myWords=myString.Split('');

Console.WriteLine("Addingdoublequotesareoundwords:H);

foreach(stringmyWordinmyWords)

(

Console.Write("\n{0}\n”,myWord);

}

}

Chapter6:Functions

Exercise1

Q.Thefollowingtwofunctionshaveerrors.Whatarethey?

staticboolWrite()

(

Console.WriteLine("Textoutputfromfunction.");

}

staticvoidmyFunction(stringlabel,paramsint[]args,boolshowLabel)

(

if(showLabel)

Console.WriteLine(label);

foreach(intiinargs)

Console.WriteLine("{0}n,i);

}

A.Thefirstfunctionhasareturntypeofbool,butdoesn'treturnaboolvalue.

Thesecondfunctionhasaparamsargument,butitisn'tattheendoftheargumentlist.

Exercise2

Q.Writeanapplicationthatusestwocommandlineargumentstoplacevaluesintoastringandan

integervariablerespectively,thendisplaythesevalues.

A.

staticvoidMain(string[]args)

(

if(args.Length!=2)

(

Console.WriteLine("Twoargumentsrequired.");

return;

)

stringparaml=args[0];

intparam2=Convert.Tolnt32(args[1]);

Console.WriteLine("Stringparameter:{0}”,paraml);

Console.WriteLine(nIntegerparameter:{0}“,param2);

}

Notethatthisanswercontainscodethatchecksthat2argumentshavebeensupplied,which

wasn'tpartoftheQuestionbutseemslogicalinthissituation.

Exercise3

Q.CreateadelegateanduseittoimpersonatetheConsole.ReadLine()functionwhenasking

foruserinput.

A.

classProgram

|

delegatestringReadLineDelegate();

staticvoidMain(string[]args)

(

ReadLineDelegatereadLine=newReadLineDelegate(Console.ReadLine);

Console.WriteLine("Typeastring:n);

stringuserinput=readLine();

Console.WriteLine(nYoutyped:{0}“,userInput);

Exercise4

Q.Modifythefollowingstructtoincludeafunctionthatreturnsthetotalpriceofanorder:

structorder

publicstringitemName;

publicintunitcount;

publicdoubleunitCost;

structorder

publicstringitemName;

publicintunitCount;

publicdoubleunitCost;

publicdoubleTotalCost()

(

returnunitCount*unitCost;

Exercise5

Q.Addanotherfunctiontotheorderstructthatreturnsaformattedstringasfollows,whereitalic

entriesenclosedinanglebracketsarereplacedbyappropriatevalues:

OrderInformation:<unitcount><itemname>itemsat$<unitcost>each,total

cost$<totalcost>

structorder

publicstringitemName;

publicintunitCount;

publicdoubleunitcost;

publicdoubleTotalCost()

(

returnunitCount*unitCost;

)

publicstringInfo()

(

returnnOrderinformation:"+unitCount.ToString()+"”+itemName+

nitemsat$”+unitcost.ToString()+neach,totalcost$”+

TotalCost().ToString();

)

)

Chapter7:DebuggingandErrorHandling

Exercise1

Q.t4UsingTrace.WriteLine()ispreferabletousingDebug.WriteLine()becausethe

DebugversiononlyworksindebugbuildsZ,Doyouagreewiththisstatement?Why?

A.Thisstatementisonlytrueforinformationthatyouwanttomakeavailableinallbuilds.More

often,youwillwantdebugginginformationtobewrittenoutonlywhendebugbuildsareused.In

thissituation,theDebug.WriteLine()versionispreferable.

UsingtheDebug.WriteLine()versionalsohastheadvantagethatitwillnotbecompiledinto

releasebuilds,thusreducingthesizeoftheresultantcode.

Exercise2

Q.Providecodeforasimpleapplicationcontainingaloopthatgeneratesanerrorafter5000cycles.

UseabreakpointtoenterBreakmodejustbeforetheerroriscausedonthe5000thcycle.(Note:a

simplewaytogenerateanerroristoattempttoaccessanonexistentarrayelement,suchas

myArray[1000]inanarraywithahundredelements.)

A.

staticvoidMain(string[]args)

(

for(inti=1;i<10000;i++)

(

Console.WriteLine("Loopcycle{0}",i);

if(i==5000)

(

Console.WriteLine(args[999]);

InVS,abreakpointcouldbeplacedonthefollowingline:

Console.WriteLine(nLoopcycle{0}”,i);

Thepropertiesofthebreakpointshouldbemodifiedsuchthatthehitcountcriterionis“break

whenhitcountisequalto5000.^^

InVCE,abreakpointcouldbeplacedonthelinethatcausestheerrorbecauseyoucannotmodify

thepropertiesofbreakpointsinVCEinthisway.

Exercise3

Q."finallycodeblocksexecuteonlyifacatchblockisn'texecuted."Trueorfalse?

A.False,finallyblocksalwaysexecute.Thismayoccurafteracatchblockhasbeenprocessed.

Exercise4

Q.Giventheenumerationdatatypeorientationdefinedinthefollowingcode,writean

applicationthatusesStructuredExceptionHandling(SEH)tocastabytetypevariableintoan

orientationtypevariableinasafeway.(Note:youcanforceexceptionstobethrownusing

thecheckedkeyword,anexampleofwhichisshownhere.Thiscodeshouldbeusedinyour

application.)

enumorientation:byte

(

north=1,

south=2,

east=3,

west=4

)

myDirection=checked((orientation)myByte);

A.

staticvoidMain(string[]args)

(

orientationmyDirection;

for(bytemyByte=2;myByte<10;myByte++)

(

try

(

myDirection=checked((orientation)myByte);

if((myDirection<orientation.north)II

(myDirection>orientation.west))

{

thrownewArgumentOutOfRangeException("myByte",myByte,

"Valuemustbebetween1and4");

)

}

catch(ArgumentOutOfRangeExceptione)

(

//IfthissectionisreachedthenmyByte<1ormyByte>4.

Console.WriteLine(e.Message);

Console.WriteLine("Assigningdefaultvalue,orientation.north.");

myDirection=orientation.north;

}

Console.WriteLine("myDirection={0}n,myDirection);

Thisisabitofatrickquestion.Becausetheenumerationisbasedonthebytetypeanybyte

valuemaybeassignedtoit,evenifthatvalueisn'tassignedanameintheenumeration.Inthis

codeyougenerateyourownexceptionifnecessary.

Chapter8:IntroductiontoObject-OrientedProgramming

Exercise1

Q.WhichofthefollowingarereallevelsofaccessibilityinOOP?

a.Friend

b.Public

c.Secure

d.Private

e.Protected

f.Loose

g.Wildcard

A.(b)public,(d)private,and(e)protectedarereallevelsofaccessibility.

Exercise2

Q."Youmustcallthedestructorofanobjectmanually,oritwillwastememory."TrueorFalse?

A.False.Youshouldnevercallthedestructorofanobjectmanually.The.NETruntimeenvironment

doesthisforyouduringgarbagecollection.

Exercise3

Q.Doyouneedtocreateanobjecttocallastaticmethodofitsclass?

A.No,youcancallstaticmethodswithoutanyclassinstances.

Exercise4

Q.DrawaUMLdiagramsimilartotheonesshowninthischapterforthefollowingclassesand

interface:

*AnabstractclasscalledHotDrinkthathasthemethodsDrink(),AddMilk(),and

AddSugar(),andthepropertiesMilk,

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論