C_入门经典课后习题答案.pdf

上传人:无*** 文档编号:90887920 上传时间:2023-05-18 格式:PDF 页数:144 大小:7.52MB
返回 下载 相关 举报
C_入门经典课后习题答案.pdf_第1页
第1页 / 共144页
C_入门经典课后习题答案.pdf_第2页
第2页 / 共144页
点击查看更多>>
资源描述

《C_入门经典课后习题答案.pdf》由会员分享,可在线阅读,更多相关《C_入门经典课后习题答案.pdf(144页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Beginning Visual C#2005Exercise AnswersChapter 1:Introducing C#No Exercises.Chapter 2:Writing a C#ProgramNo Exercises.Chapter 3:Variables and ExpressionsExercise 1Question:In the following code,how would we refer to the name g r e a t from code inthe namespace fabulous?namespace fabulous(/code in fa

2、bulous namespace)namespace super(namespace smashing(/great name defined)Answer:super.smashing.greatExercise 2Question:Which of(he following is not a legal variable name:a)m yV ariablelsG oodb)99Flakec)_ f lo o rd)tim e2G etJiggyW idlte)w Answer:b because it starts with a numberande because it contai

3、ns a full stopExercise 3Question:Is the string s u p e r c a lif r a g ilis tic e x p ia lid o c io u s too big to fit ina s tr i n g variable?Why?Answer:No,there is no theoretical limit to the size of a string that may be contained in as tr i n g variable.Exercise 4Question:By considering operator

4、precedence,list the steps involved in the computationof the following expression:resultVar+=varl*var2+var3 var4/var5;Answer:The*and/operators have the highest precedence here,followed by+,andfinally+=.The precedence in the exercise can be illustrated using parentheses as follows:resultVar+=(varl*var

5、2)+var3)(var4/var5);Exercise 5Question:Write a console application that obtains four in t values from the user anddisplays their product.Answer:static void Main(string args)(int firstNumber,secondNumber,thirdNumber,fourthNumber;Console.WriteLine(Give me a number:n);firstNumber=Convert.ToInt32(Consol

6、e.ReadLine();Console.WriteLine(Give me another number:);secondNumber=Convert.Tolnt32(Console.ReadLine();Console.Writ eLine(Give me another number:;thirdNumber=Convert.ToInt32(Console.ReadLine();Console.WriteLine(Give me another number:n);fourthNumber=Convert.Tolnt32(Console.ReadLine();Console.WriteL

7、ine(The product of 0,1z 2,and 3 is4.”,firstNumber,secondNumber,thirdNumber,fourthNumber,firstNumber*secondNumber*thirdNumber*fourthNumber);Note that C o n v ert.T olnt32()is used here,which isnt covered in the chapter.Chapter 4:Flow ControlExercise 1Question:If you have two integers stored in variab

8、les v a rl and var2,what Boolean testcan you perform to see if one or the other of them(but not both)is greater than 10?Answer:(varl 10)A(var2 10)Exercise 2Question:Write an application that includes the logic from Exercise 1,obtains twonumbers from the user and displays them,but rejects any input w

9、here both numbers aregreater than 10 and asks for two new numbers.Answer:static void Main(string args)(bool numbersOK=false;double varl,var2;varl=0;var2=0;while(!numbersOK)Console.WriteLine(Give me a number:);varl=Convert.ToDouble(Console.ReadLine();Console.Writ eLine(Give me another number:;var2=Co

10、nvert.ToDouble(Console.ReadLine();if(varl 10)人(var2 10)(numbersOK=true;else(if(varl=10)&(var2=10)(numbersOK=true;else(Console.WriteLine(Only one number may be greater than10.);)Console.WriteLine(You entered 0 and 1.,varl,var2);Note that this can be performed better using different logic,for example:

11、static void Main(string args)(bool numbersOK=false;double varl,var2;varl=0;var2=0;while(!numbersOK)(Console.WriteLine(Give me a number:n);varl=Convert.ToDouble(Console.ReadLine();Console.Writ eLine(Give me another number:;var2=Convert.ToDouble(Console.ReadLine();if(varl 10)&(var2 10)(Console.WriteLi

12、ne(Only one number may be greater than10.);)else(numbersOK=true;Console.Writ eLine(*You entered 0 and 1.z varl,var2);)Exercise 3Question:What is wrong with the following code?int i;for(i=1;i=10;i+)(if(i%2)=0)continue;Console.WriteLine(i);)Answer:The code should read:int i;for(i=1;i=10;i+)(if(i%2)=0)

13、continue;Console.WriteLine(i);)Using the=assignment operator instead of the Boolean=operator is a very commonmistake.Exercise 4Question:Modify the Mandelbrot set application to request image limits from the userand display the chosen section of the image.The current code outputs as many charactersas

14、 will fit on a single line of a console application.Consider making every image chosenfit in the same amount of space to maximize the viewable area.Answer:static void Main(string args)double realCoord,imagCoord;double realMax=1.77;double realMin=-0.6;double imagMax=-1.2;double imagMin=1.2;double rea

15、lStep;double imagStep;double realTemp,imagTemp,realTemp2,arg;int iterations;while(true)realStep=(realMax-realMin)/79;imagStep=(imagMax-imagMin)/48;for(imagCoord=imagMin;imagCoord=imagMax;imagCoord+=imagStep)for(realCoord=realMin;realCoord=realMax;realCoord+=realStep)iterations=0;realTemp=realCoord;i

16、magTemp=imagCoord;arg=(realCoord*realCoord)+(imagCoordimagCoord);while(arg 4)&(iterations 40)realTemp2=(realTemp*realTemp)-(imagTempimagTemp)-realCoord;imagTemp=(2*realTemp*imagTemp)-imagCoord;realTemp=realTemp2;arg=(realTemp*realTemp)+(imagTempimagTemp);iterations+=1;)switch(iterations%4)(case 0:Co

17、nsole.Write(.”);break;case 1:Console.Write(M o,);break;case 2:Console.Write(n0n);break;case 3:Console.Write(n0*);break;Console.Write(nnn);Console.WriteLine(Current limits:);Console.WriteLine(realCoord:from 0 to 1,realMin,realMax);Console.WriteLine(imagCoord:from 0 to 1*,imagMin,imagMax);Console.Writ

18、eLine(Enter new limits:n);Console.WriteLine(”realCoord:from:);realMin=Convert.ToDouble(Console.ReadLine();Console.WriteLine(realCoord:to:M);realMax=Convert.ToDouble(Console.ReadLine();Console.WriteLine(*imagCoord:from:);imagMin=Convert.ToDouble(Console.ReadLine();Console.WriteLine(nimagCoord:to:n);i

19、magMax=Convert.ToDouble(Console.ReadLine();)Chapter 5:More About VariablesExercise 1Question:Which of the following conversions cant be performed implicitly:a)i n t to s h o rtb)s h o rt to in tc)bool to s tr i n gd)b y te to f lo a tAnswer:Conversions a and c can*t be performed implicitly.Exercise

20、2Question:Give the code for a c o lo r enumeration based on the s h o rt type containingthe colors of the rainbow plus black and white.Can this enumeration be based on theb y te type?Answer:enum color:short(Red,Orange,Yellow,Green,Blue,Indigo,Violet,Black.,White)Yes,because the b y te type can hold

21、numbers between 0 and 255,so byte-basedenumerations can hold 256 entries with individual values,or more if duplicate values areused for entries.Exercise 3Question:Modify the Mandelbrot set generator example from the last chapter to use thefollowing s t r u c t for complex numbers:struct imagNum(publ

22、ic double real,imag;)Answer:static void Main(string args)(imagNum coord,temp;double realTemp2,arg;int iterations;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

23、)+(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)case 0:Console.Write(.”);break;ca

24、se 1:Console.Write(n o,);break;case 2:Console.Write(nO);break;case 3:Console.Write(n0*);break;)Console.Write(nnn);)Exercise 4Question:Will the following code compile?Why?string blab=new string5string5=5th string.Answer:No,for the following reasons:1 End of statement semicolons are missing.1 2nd line

25、 attempts to access a non-existent 6th element of blab.1 2nd line attempts to assign a string that isnt enclosed in double quotes.Exercise 5Question:Write a console application that accepts a string from the user and outputs astring with the characters in reverse order.Answer:static void Main(string

26、 args)(Console.WriteLine(Enter a string:);string myString=Console.ReadLine();string reversedString=n;for(int index=myString.Length-1;index=0;index-)(reversedString+=myStringindex;)Console.WriteLine(Reversed:0,reversedString);)Exercise 6Question:Write a console application that accepts a string and r

27、eplaces all occurrences ofthe string uno with yes”.Answer:static void Main(string args)(Console.WriteLine(Enter a string:);string myString=Console.ReadLine();myString=myString.Replace(nnon z“yes”);Console.Writ eLine(Replaced*no n with nyesn:0”,myString);)Exercise 7Question:Write a console applicatio

28、n that places double quotes around each word in astring.Answer:static void Main(string args)(Console.WriteLine(Enter a string:);string myString=Console.ReadLine();myString=*n+myString.Replace(,n)+1 1 H;Console.WriteLine(Added double quotes areound words:0”,myString);Or using S tr in g.S p l i t():st

29、atic void Main(string args)Console.WriteLine(Enter a string:);string myString=Console.ReadLine();string myWords=myString.Split(*);Console.WriteLine(Adding double quotes areound words:n);foreach(string myWord in myWords)(Console.Write(n*0”,myWord);)Chapter 6:FunctionsExercise 1Question:The following

30、two functions have errors.What are they?static bool Write()(Console.WriteLine(Text output from function.n);static void myFunction(string label,params int args,bool showLabel)(if(showLabel)Console.WriteLine(label);foreach(int i in args)Console.WriteLine(n0n,i);Answer:The first function has a return t

31、ype of bool,but doesnt return a bool value.The second function has a params argument,but this argument isnt at the endof the argument list.Exercise 2Question:Write an application that uses two command line arguments to place valuesinto a string and an integer variable respectively,then display these

32、 values.Answer:static void Main(string args)(if(args.Length!=2)(Console.WriteLine(Tv/o arguments required.;return;)string paraml=args0;int param2=Convert.ToInt32(args1);Console.WriteLine(String parameter:0,paraml);Console.WriteLine(Integer parameter:0“,param2);Note that this answer contains code tha

33、t checks that 2 arguments have been supplied,which wasnt part of the question but seems logical in this situation.Exercise 3Question:Create a delegate and use it to impersonate the C o n so le.ReadLine()function when asking for user input.Answer:class Classi(delegate string ReadLineDelegate();static

34、 void Main(string args)(ReadLineDelegate readLine=newReadLineDelegate(Console.ReadLine);Console.WriteLine(Type a string:n);string userinput=readLine();Console.WriteLine(You typed:0”,userinput);)Exercise 4Question:Modify the following s tr u c t to include a function that returns the total priceof an

35、 order:struct order(public string itemName;public int unitcount;public double unitcost;Answer:struct order(public string itemName;public int unitcount;public double unitcost;public double Totalcost()(return unitcount*unitcost;)Exercise 5Question:Add another function to the o rd e r s t r u c t that

36、returns a formatted string asfollows,where italic entries enclosed in angle brackets are replaced by appropriate values:Order Information:items at$each,total cost$.Answer:struct orderpublic string itemName;public int unitcount;public double unitcost;public double TotalCost()(return unitcount*unitcos

37、t;)public string Info()(return Order information:+unitCount.ToString()+”+itemName+items at$n+unit Cost.ToString()+n each,total cost$+TotalCost().ToString();)Chapter 7;Debugging and Error HandlingExercise 1Question:Using T race.W riteL ine()is preferable to using Debug.W riteL ine()as the Debug versi

38、on only works in debug builds.Do you agree with this statement?Why?Answer:This statement is only true for information that you want to make available in allbuilds.More often,you will want debugging information to be written out only whendebug builds are used.In this situation,the Debug.W riteL ine()

39、version is preferable.Using the Debug.W riteL ine()version also has the advantage that it will not becompiled into release builds,thus reducing the size of the resultant code.Exercise 2Question:Provide code for a simple application containing a loop that generates an errorafter 5000 cycles.Use a bre

40、akpoint to enter break mode just before the error is caused onthe 5000th cycle.(Note:a simple way to generate an error is to attempt to access a nonexistent array element,such as myArray 1000 in an array with a hundred elements.)Answer:static void Main(string args)(for(int i=1;i 10000;i+)(Console.Wr

41、iteLine(Loop cycle 0“,i);if(i=5000)(Console.WriteLine(args999);)In the preceding code a breakpoint could be placed on the following line:Console.WriteLine(Loop cycle 0“,i);The properties of the breakpoint should be modified such that the hit count criterion isbreak when hit count is equal to 5000n.E

42、xercise 3Question:f i n a l l y code blocks only execute if a c a tc h block isnt executed.1 True orfalse?Answer:False.Finally blocks always execute.This may occur after a c a tc h block hasbeen processed.Exercise 4Question:Given the enumeration data type o r i e n t a t i o n defined below,write an

43、application that uses SEH to cast a b y te type variable into an o r i e n t a t i o n typevariable in a safe way.Note that you can force exceptions to be thrown using thech eck ed keyword,an example of which is shown below.This code should be used inyour application,enum orientation:byte(north=1,so

44、uth=2,east=3,west=4myDirection=checked(orientation)myByte);Answer:static void Main(string args)orientation myDirection;for(byte myByte=2;myByte 10;myByte+)trymyDirection=checked(orientation)myByte);if(myDirection orientation.west)throw new ArgumentOutOfRangeException(nmyByte,myByte,Value must be bet

45、ween 1and 4;catch(ArgumentOutOfRangeException e)/If this section is reached then myByte 4.Console.WriteLine(e.Message);Console.WriteLine(Assigning default value,orientation.north.;myDirection=orientation.north;Console.WriteLine(myDirection=0”,myDirection);)Note that this is a bit of a trick question

46、.Since the enumeration is based on the b y te typeany b y te value may be assigned to it,even if that value isnt assigned a name in theenumeration.In the preceding code you generate your own exception if necessary.Chapter 8:Introduction to Object-OrientedProgrammingExercise 1Question:Which of the fo

47、llowing are real levels of accessibility in OOP?1 Friend1 Public1 Secure1 Private1 Protected1 LooseWildcardAnswer:Public,private,and protected are real levels of accessibility.Exercise 2Question:You must call the destructor of an object manually,or it will waste memory.1True or False?Answer:False.Yo

48、u should never call the destructor of an object manuallythe.NETruntime environment will do this for you during garbage collection.Exercise 3Question:Do you need to create an object in order to call a static method of its class?Answer:No,you can call static methods without any class instances.Exercis

49、e 4Question:Draw a UML diagram similar to the ones shown in this chapter for thefollowing classes and interface:1 An abstract class called HotDrink that has the methods D rink(),AddMilk(),andAddSugar(),and the properties M ilk and Sugar.1 An interface called ICup that has the methods Ref i l l()and

50、Wash(),and theproperties C olor and Volume.1 A class called CupOfCof fee that derives from HotDrink,supports the ICupinterface,and has the additional property BeanType.1 A class called CupOfTea that derives from HotDrink,supports the ICup interface,and has the additional property LeafType.Answer:+Dr

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 教育专区 > 教案示例

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁