Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Tc = (5/9)*(Tf-32);

When implemented in C#, the formula looks like this:

double fahrenheit = 100;

double celcius = 5.0 / 9.0 * fahrenheit - 32;

Console.WriteLine("{0:##.##} degrees C",celcius); //---23.56 degrees C---

But this produces a wrong answer because 5.0 / 9.0and fahrenheit - 32must be evaluated separately before their results are multiplied to get the final answer. What's happened is that, according to the precedence table, 5.0 / 9.0 * fahrenheitis evaluated first and then 32 is subtracted from the result. This gives the incorrect answer of 23.56 degrees C.

To correct this, you use parentheses to group all the expressions that need to be evaluated first, like this:

double fahrenheit = 100;

double celcius = (5.0 / 9.0) * (fahrenheit - 32);

Console.WriteLine("{0:##.##} degrees C",celcius); //---37.78 degrees C---

This code gives the correct answer of 37.78 degrees C.

Preprocessor Directives

So far the programs you have seen in this chapter are pretty straightforward; you compile the entire program and run it from beginning until end. However, there are times when you want to inject debugging statements into your program — generally using methods such as Console.WriteLine()or MessageBox.Show()— and then remove them when the program is ready for deployment. But one common mistake is that programmers often forget to remove all those statements after debugging. The end result is that production code often contains many redundant code statements.

A better way is to instruct the C# compile to conditionally omit some of the code during compilation. For example, you can delineate some parts of your code as debugging statements that should not be present in the production code. To do so, you can use preprocessor directives, which are special instructions to a special program (known as the processor) that will prepare your code before sending it to the compiler. C# supports the following preprocessor directives, most of which are discussed in the following sections:

#define #elif #line #pragma warning

#undef #endif #region #pragma checksum

#if #warning #endregion

#else #error #pragma

#define and #undef

The #definepreprocessor directive allows you to define a symbol so that you can use the #ifpreprocessor directive to evaluate and then make conditional compilation. To see how the #define preprocessor directive works, assume that you have a console application named TestDefine(saved in C:\) created using Visual Studio 2008 (see Figure 3-12).

Figure 312 The Main method is located in the Programcs file The program - фото 93

Figure 3-12

The Main() method is located in the Program.cs file. The program basically asks the user to enter a number and then sums up all the odd number from 1 to that number:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace TestDefine {

class Program {

static void Main(string[] args) {

Console.Write("Please enter a number: ");

int num = int.Parse(Console.ReadLine());

int sum = 0;

for (int i = 1; i <= num; i++) {

//---sum up all odd numbers---

if (i % 2 == 1) sum += i;

}

Console.WriteLine(

"Sum of all odd numbers from 1 to {0} is {1}",

num, sum);

Console.ReadLine();

}

}

}

Suppose that you want to add some debugging statements to the program so that you can print out the intermediate results. The additional lines of code are highlighted:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace TestDefine {

class Program {

static void Main(string[] args) {

Console.Write("Please enter a number: ");

int num = int.Parse(Console.ReadLine());

int sum = 0;

for (int i = 1; i <= num; i++) {

//---sum up all odd numbers---

if (i % 2 == 1)

{

sum += i;

Console.WriteLine("i={0}, sum={1}", i, sum);

}

}

Console.WriteLine(

"Sum of all odd numbers from 1 to {0} is {1}",

num, sum);

Console.ReadLine();

}

}

}

You do not want the debugging statements to be included in the production code so you first define a symbol (such as DEBUG) using the #definepreprocessor directive and wrap the debugging statements with the #ifand #endifpreprocessor directives:

#define DEBUG

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace TestDefine {

class Program {

static void Main(string[] args) {

Console.Write("Please enter a number: ");

int num = int.Parse(Console.ReadLine());

int sum = 0;

for (int i = 1; i <= num; i++) {

//---sum up all odd numbers---

if (i % 2 == 1) {

sum += i;

#if DEBUG

Console.WriteLine("i={0}, sum={1}", i, sum);

#endif

}

}

Console.WriteLine(

"Sum of all odd numbers from 1 to {0} is {1}",

num, sum);

Console.ReadLine();

}

}

}

DEBUGis a common symbol that developers use to indicate debugging statements, which is why most books use it in examples. However, you can define any symbol you want using the #definepreprocessor directive.

Before compilation, the preprocessor will evaluate the #ifpreprocessor directive to see if the DEBUGsymbol has been defined. If it has, the statement(s) wrapped within the #ifand #endifpreprocessor directives will be included for compilation. If the DEBUGsymbol has not been defined, the statement — the statement(s) wrapped within the #ifand #endifpreprocessor — will be omitted from the compilation.

To test out the TestDefineprogram, follow these steps:

1. Launch the Visual Studio 2008 command prompt (Start→Programs→Microsoft Visual Studio 2008→Visual Studio Tools→Visual Studio 2008 Command Prompt).

2. Change to the path containing the program (C:\TestDefine).

3. Compile the application by issuing the command:

csc Program.cs

4. Run the program by issuing the command:

Program.exe

Figure 3-13 shows the output of the application. As you can see, the debugging statement prints out the intermediate results.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x