Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Data Type Problems

To a human being, the integer 3 is just like the real number 3.0. However, in a computer system, the int value 3 is stored differently than the long value 3. The float and double versions of these numbers are even more different. The computer can convert between these types, but often with problems. Take a look at this segment of the Simple Math program:

//division by integers can cause problems Console.WriteLine("5/4 = {0}", 5 / 4);

In the corresponding output, you see a surprising result.

Output:

5/4 = 1

Of course, 5 divided by 4 equals 1.25, so something went wrong. C# recognizes that both 5 and 4 are integers, so it assumes that the result of any operation between them should also be an integer. I fixed this problem by forcing 4 and 5 to be read as floating−point variables, like this:

Console.WriteLine("5f/4f = {0}", 5f / 4f);

Math Operators

Now that you know how to represent numbers, you can do basic math on them. All the basic operators work as you might expect. The plus sign (+) is used for addition, the minus sign (−) for subtraction, the forward slash (/) for division, and the asterisk (*) for multiplication.

Converting Variables

Knowing how to convert variables from one data type to another is important for programmers. C# offers many ways to perform these conversions. Sometimes, as in the Simple Math program, the conversion is done automatically. Other times, you have to do the conversion explicitly. Fortunately, C# makes variable conversion easy. As usual, it makes sense to look at a working program (see Figure 2.4):

Figure 2.4: Although the console works only with string values, you can convert strings to whatever

37

type of variable you wish.

using System;

namespace ConvertDemo

{

///<summary>

///demonstrates various types of variable conversions

///Andy Harris, 11/09/01

///</summary>

class ConvertDemo

{

static void Main()

{

int myInt; double myDouble; string myString;

myInt = 5;

//copying an int to a double causes no problems myDouble = myInt;

Console.WriteLine("myDouble is {0}.", myDouble);

//copying

a double to an int won't

work!

myDouble = 3.5;

 

 

//myInt =

myDouble;

//this line

causes an error

//Console.WriteLine(myInt);

 

//You can

explicitly cast, but you

might lose data

myInt = (int)myDouble;

 

 

Console.WriteLine("After casting, myInt = {0}.", myInt);

myString = myDouble.ToString(); Console.WriteLine("myDouble as a String: {0}", myString);

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

Console.WriteLine("myString converted to double: {0}",

Convert.ToDouble(myString));

} // end main } // end class

}// end namespace

Trick Some programmers prefer some alternate syntaxes, such as myFloat.Parse(someString) or myInt.Parse(someString). However, the Convert syntax works on all variables types, so it’s a pretty convenient solution.

To illustrate some key conversion ideas, I created an int, a double, and a string. These are, by far, the most common variable types you will use. I started by assigning the value 5 (an integer value) to myInt. Then, I copied the value of myInt to the myDouble variable. This caused no problems because a double can easily hold all the information in an int. However, the next few lines of code assign the value 3.5 to myDouble and then try to copy the value of myDouble to myInt. In the preceding source code, I’ve placed the comment characters before this line so it will not execute. This is commonly called commenting out code.

I commented out that particular line of code because it causes the system to crash. You cannot copy a double value to an int because doubles have more information (namely, the information after the decimal point). You can’t even copy the value 3.0 to an int variable directly because 3.0 is a

38

double value.

Explicit Casting

You can convert a double value to an integer value, but you will lose some information along the way. Take a look at this line:

myInt = (int)myDouble;

This line copies the value of myDouble to myInt successfully, but it does so by utilizing a trick called casting, in which the term (int) tells the compiler to convert the value immediately following into an integer value. This results in a loss of data, but it works. You can use this type of operation to convert any numeric data types.

The Convert Object

Strings are not like other types of data because the amount of information necessary to store a string can vary, based on the length of the string. You don’t have to worry about this, but you should know that the conversion techniques that work between numbers do not work the same way with string variables. The string value "123" is not the same as the int value 123 or the double value 123.0. You cannot use a casting operation to convert to or from a string value. Therefore,

myInt = (int)"123"

does not work, and

myString = (string) 123

does not work, either.

In the Real World

Converting numeric data to strings is important because all the user generally sees is text information. When the user types something, the program usually sees it as a string value. For example, the Console.ReadLine() method always results in a string value. If you want to get a number from the user, you have to take the string from the ReadLine() method and convert it to a number yourself.

Fortunately, C# has an object that specializes in converting variables between types, and it always works. The convert object, pictured in Figure 2.5, is a special object that provides several useful methods. Methods are actions an object can perform. Most of the convert object’s methods convert data from one type to another.

39

Figure 2.5: The convert object can convert nearly any variable type to any other variable type.

The Convert class is part of the System namespace, so you already have access to it. To use the class, you call one of its methods. For example,

myInt = Convert.ToInt32("123");

converts the string value "123" into an integer and stores that value into myInt. Likewise, the statement

myString = Convert.ToString(123);

takes the int value 123 and converts it into a string for storage in the myString variable. Of course, you usually won’t use the Convert class with literal values, as I’ve done in these examples. Generally, you stuff a variable in the ToInt32() or ToString() method, like this:

myInt = Convert.ToInt32(myString);

Because you sometimes grab a numeric value from the console, you often simply put the Console.ReadLine() method inside the ToInt() parentheses, like this:

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

Trap The convert object isn’t foolproof. If you let the user type in data, you don’t have any way to know whether he or she added a decimal point. You might be tempted to write code like this: myInt = Convert.ToInt32(Console.ReadLine()); This code works great if the user types an integer, but if the user enters a real number with a decimal point, your program will crash. It is safer to do the same operation in two steps, like this: myDouble = Convert.ToDouble(Console.ReadLine()); myInt = (int)

myDouble; The compiler will have no problem converting a

40

Соседние файлы в предмете Программирование на C++