版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 新員工培訓(xùn)匯報(bào)
- 大班科學(xué)活動(dòng)仿生現(xiàn)象
- 名師班主任培訓(xùn)心得
- 數(shù)控車(chē)削加工技術(shù) 教案 項(xiàng)目十 螺紋車(chē)削工藝及編程
- 13.1 分子熱運(yùn)動(dòng)(6大題型)(含答案解析)
- 新疆喀什地區(qū)2024-2025學(xué)年高二上學(xué)期期中地理試卷(無(wú)答案)
- 廣東順德德勝學(xué)校2024-2025學(xué)年高二上學(xué)期10月月考英語(yǔ)試題(含答案無(wú)聽(tīng)力原文及音頻)
- 2025屆湖北省部分高中高三上學(xué)期11月期中聯(lián)考數(shù)學(xué)試題(含答案)
- 2024-2025學(xué)年安徽省六安市裕安區(qū)六安九中九年級(jí)(上)月考物理試卷(10月份)(含答案)
- T-YNZYC 0106-2023 綠色藥材 烏天麻產(chǎn)地環(huán)境標(biāo)準(zhǔn)
- 啟封密閉排放瓦斯方案及安全技術(shù)措施
- 2023-2024年湖北省鄂東南聯(lián)盟高一上學(xué)期期中聯(lián)考物理試題(解析版)
- 2023年康復(fù)醫(yī)學(xué)治療技術(shù)(士)考試題庫(kù)匯總500道含解析253
- 獎(jiǎng)牌施工方案
- 加油站可行性研究報(bào)告范文
- 國(guó)家獎(jiǎng)學(xué)金申請(qǐng)審批表模板
- 物理化學(xué)二氧化碳和硫的相圖
- 接地裝置及接地電阻檢測(cè)記錄表
- 新員工入職考核評(píng)估表
- 國(guó)開(kāi)2023秋人文英語(yǔ)4形考任務(wù)1-4參考答案
- 癲癇概述PPT(共47張PPT)
評(píng)論
0/150
提交評(píng)論