《C#入门经典课后习题答案.docx》由会员分享,可在线阅读,更多相关《C#入门经典课后习题答案.docx(79页珍藏版)》请在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 great from code in the namespace fabulous?namespace fabulous/ code i
2、n fabulous namespacenamespace smashing/ great name definedAnswer:super.smashing.greatExercise 2Question: Which of the following is not a legal variable name:a) myVariablelsGoodb) 99Flakec) _floord) time2GetJiggyWidlt e) wrox. comAnswer: b 一 because it starts with a number and e because it contains a
3、 full stopExercise 3Question: Is the string Msupercalif ragilisticexpialidocious*1 too big to fit in a string variable? Why?Answer: No, there is no theoretical limit to the size of a string that may be contained in a string variable.Exercise 4Question: By considering operator precedence, list the st
4、eps involved in the computation of the following expression:resultVar += varl * var2 + var3 var4 / var5;Answer: The * and / operators have the highest precedence here, followed by +, , and finally +=. The precedence in the exercise can be illustrated using parentheses as follows:resultVar += (varl *
5、 var2) + var3) 10) A (var2 10)Exercise 2Question: Write an application that includes the logic from Exercise 1, obtains two numbers from the user and displays them, but rejects any input where both numbers are greater than 10 and asks for two new numbers.Answer:static void Main(string args)bool numb
6、ersOK = false;double varl, var2;varl = 0;var2 = 0;while (!numbersOK)Console.WriteLine(Give me a number:);varl = Convert.ToDouble(Console.ReadLine();Console.WriteLine(Give me another number:);var2 = Convert.ToDouble(Console.ReadLine(); if (varl 10) A (var2 10)numbersOK = true;elseif (varl = 10) & (va
7、r2 10) & (var2 10)Console.WriteLine(Only one number may be greater than 10.);elsenumbersOK = true;Console.WriteLine(You entered 0 and 1., varl, var2);Exercise 3Question: What is wrong with the following ctxle?int i;for (i = 1; i = imagMax; imagCoord += imagStep)for (realCoord = realMin; realCoord =
8、realMax realCoord += realStep)iterations = 0;realTemp = realCoord;imagTemp = imagCoord;arg = (realCoord * realCoord) + (imagCoordimagCoord);while (arg 4) & (iterations = -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
9、.imag = coord.imag;arg = (coord.real * coord.real) + (coord.imagcoord.imag);while (arg 4) & (iterations = 0; index)reversedString += myStringindex;Console.WriteLine(Reversed: 0, reversedString);Exercise 6Question: Write a console application that accepts a string and replaces all occurrences of the
10、string *no with yes.Answer:static void Main(string args)Console . Writ eLine ( Enter a string: *); string myString = Console.ReadLine(); myString = myString.Replace(no, yes);Console.WriteLine(Replaced no with yes: 0), myString);Exercise 7Question: Write a console application that places double quote
11、s around each word in a string.Answer:static void Main(string args)Console.WriteLine(Enter a string:); string myString = Console.ReadLine(); myString = + myString.Replace( , ) + ;Console.WriteLine(Added double quotes areound words: 0 myString);Or using String. Split ():static void Main(string args)C
12、onsole.WriteLine(Enter a string:); string myString = Console.ReadLine(); string myWords = myString.Split(* *);Console.WriteLine(Adding double quotes areound words:); foreach (string myWord in myWords)Console.Write(0 , myWord);Chapter 6: FunctionsExercise 1Question: The following two functions have e
13、rrors. What are they?static bool Write() (Console.WriteLine(Text output from function.static void myFunction(string label, params int args, bool showLabel)if (showLabel)Console.WriteLine(label); foreach (int i in args)Console.WriteLine(0, i);Answer: The first function has a return type of bool, but
14、doesnt return a bool value.The second function has a params argument, but this argument isnt at the end of the argument list.Exercise 2Question: Write an application that uses two command line arguments to place values into a string and an integer variable respectively, then display these values.Ans
15、wer:static void Main(string args)if (args.Length != 2)Console.WriteLine(Two arguments required.); return;string paraml = args0;int param2 = Convert.ToInt32(args1);Console.WriteLine(String parameter: 0, paraml);Console.WriteLine(Integer parameter: 0, param2);which wasnt part of the question but seems
16、 logical in this situation.Exercise 3Question: Create a delegate and use it to impersonate the Console. ReadLine () function when asking for user input.Answer:class Classi (delegate string ReadLineDelegate();static void Main(string args) (ReadLineDelegate readLine = newReadLineDelegate(Console.ReadL
17、ine);Console.WriteLine(Type a string:);string userinput = readLine();Console.WriteLine(You typed: 0, userinput); ) Exercise 4Question: Modify the following struct to include a function that returns the total price of an order: struct order ( public string itemName;public int unitCount;public double
18、unitCost;Answer:struct order(public string itemName;public int unitCount;public double unitCost;public double Totalcost() (return unitCount * unitCostExercise 5Question: Add another function to the order struct that returns a formatted string as follows, where italic entries enclosed in angle bracke
19、ts 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 * unitcost;public string Info()(return Order information: + unitcount.ToString() +
20、+ itemName +“items at $ + unitcost.ToString() + “ each, total cost $ +TotalCost().ToString();Chapter 7: Debugging and Error HandlingExercise 1Question: Using Trace .WriteLine () is preferable to using Debug. WriteLine () as the Debug version only works in debug builds. Do you agree with this stateme
21、nt?Why?Answer: This statement is only true for information that you want to make available in all builds. More often, you will want debugging information to be written out only when debug builds are used. In this situation, the Debug. WriteLine () version is preferable.Using the Debug. WriteLine ()
22、version also has the advantage that it will not be compiled 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 error after 5(X)0 cycles. Use a breakpoint to enter break mode just before the e
23、rror is caused on the 50(X)th cycle. (Note: a simple way to generate an error is to attempt to access a non existent 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.WriteLine(Loop cycle , i); if (i = 500
24、0)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 is break when hit count is equal to 5000.Exercise 3Question: finally code blo
25、cks only execute if a catch block isnt executed. True or false?Answer: False. Finally blocks always execute. This may occur after a catch block has been processed.Exercise 4Question: Given the enumeration data type orientation defined below, write an application that uses SEH to cast a byte type var
26、iable into an orientation type variable in a safe way. Note that you can force exceptions to be thrown using the checked keyword, an example of which is shown below. This code should be used in your application.enum orientation : bytenorth = 1, south = 2f east = 3, west = 4myDirection = checked(orie
27、ntation)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(MmyByteM, myByte, Value must be between 1 and 4);catch (ArgumentOu
28、tOfRangeException e)/ If this section is reached then myByte Console.WriteLine(e.Message);Console.WriteLine(Assigning default value, orientation.north.);myDirection = orientation.north;Console.WriteLine(myDirection = 0, myDirection);一:一 any byte value may be assigned to it, even if that value isnt assigned a name in the enumeration. In the preceding code you generate your