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

The program has features that might not be immediately apparent. To keep the program interesting, the problems are randomly generated each time the program is run. Also, because the game is for younger children, I decided that the answers should always be positive integers. (The problems are fixed so that subtractions will never come out negative, and division problems will never have a remainder.) The program keeps track of the number of questions the user answers and gives a score based on the user’s responses.

Using Numeric Variables

A computer programmer needs to understand how computers work with information. The hardware of modern computers works with little on/off switches that work in Base−two mathematics. Some people refer to this type of mathematics as binary mathematics and use values of 1 and 0 instead of on and off switches. All information in a computer, from text to video games, is converted internally into binary numbers before the computer can do something useful with it. In the earliest days of computer programming, you had to work in binary notation to do anything.

Fortunately, modern languages such as C# spare you this tedium. You can tell the computer that you want to work with text (which programmers call strings, as you recall from Chapter 1, “Basic Input and Output: A Mini Adventure”), integers (positive and negative numbers without decimal values), real numbers (numbers with decimal values), and complex types of information, such as dates, pictures, sounds, and whatever else you can store in a computer. Although you don’t need to be fluent in binary to be a computer programmer, you do need to understand that the computer uses different tricks to translate all these kinds of data into binary information.

The Simple Math Game

Computers are good at math, but you must look out for a few things. The various types of data storage can have some surprising side effects. The following program, shown in Figure 2.3, illustrates some of the things that can go wrong.

Figure 2.3: The computer can do math, but it gave some strange results here. Is 5 divided by 4 really 1?

This program is silly but it illustrates some important points about how numbers work in computing. Take a look at the source code for this program, and I’ll explain what’s going on:

using System;

33

namespace SimpleMath

{

///<summary>

///Demonstrates basic variable stuff

///Andy Harris, 11/09/01

///</summary>

class DoMath

{

static void Main(string[] args)

{

int a = 1; int b = 2;

float c = 2.4f; float d = 4.7f;

Console.WriteLine("Math Demo"); Console.WriteLine(); Console.WriteLine();

//addition with integers works as expected Console.WriteLine("5 + 4 = {0}", 5 + 4); Console.WriteLine("{0} + {1} = {2}", a, b, a + b);

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

//dividing by floating point values works better Console.WriteLine("{0} / {1} = {2}", c, d, c/d); Console.WriteLine("5f/4f = {0}", 5f / 4f);

Console.WriteLine();

Console.WriteLine();

Console.Write("Please press \"enter\" to continue");

Console.ReadLine();

} // end main } // end class

}// end namespace

The design of this program is straightforward. The computer simply performs basic mathematical operations and reports the results. The program demonstrates important details about how numeric variables are created and used. I’ll explain how this program works in the next few sections. First, take a look at variable types.

Numeric Variable Types

C# supports a number of numeric variable types. Each type specifies a different way the numeric data is translated into binary. Table 2.1 describes several key data types in C#.

C# supports other types of variables besides the ones listed here, but for a beginning programmer, these variable types work just fine. Each type of variable takes up a specific amount of memory and is best suited for working with a particular type of number. In general, you work with two primary types of numbers in C# programming: the int and double types.

Hint The reference to unicode in the table above refers to a scheme for storing characters in binary form in computer memory. Computers have used a scheme called ASCII for many years, but C# and a number of other languages now use the unicode standard, because it provides support for most written languages, including those which do not use Roman characters.

34

Table 2.1: Selected Data Types

Type

Description

Values

Examples

bool

Boolean (true/false)

True or false

true

char

One character

Characters in English

‘a’

 

 

or other languages

 

 

 

(with unicode)

 

int

Integer (positive or negative value

–2 billion to 2

34

 

without a decimal point)

billion (roughly)

−7

long

Long integer

+/– 9 * 1018r

3L

 

 

 

−23L

float

Floating−point real number

+/– 3.5 * 1038,

1.5f

 

 

7 significant digits

−3.1415927f

double

Double−precision real number

+/– 1.7 * 10308,

−2.5

 

 

15 significant digits

3.1415

Integer Variables

You might remember from grade school that integers are positive and negative numbers and zero but not numbers that end in a decimal (or fractional) value. For example, 3, –100, and 0 are integers, but 3.14159 and –0.5 are not. Most of the time in your programming career, you will work with integer values. Although in math integers can be infinitely large or small, they aren’t in computing. Storing a number in a computer’s memory takes a finite amount of space, so the variable types are organized according to how much memory they use. The more memory a variable type uses, the larger range of numbers it can handle.

C# has two main types of integers. The int variable type uses 32 digits of binary to represent a number, meaning that an int variable values roughly between 2 billion and negative 2 billion. This range is related to the largest and smallest numbers that can be stored in 32 digits of binary math. Most of the math you do on a computer probably falls within that range, so if you don’t need a decimal point, you can make an int variable. Any time you refer to a number without a decimal point in your code, the number is interpreted as an int value. The values 5 and 4 are called literal values, because they are not variables. However, the computer still needs to assign a type to such values, and because there is no decimal point in the values, they will be interpreted as literal ints.

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

5 and 4 are int literals, but you can also create a variable that is defined as an int. Take a look at these lines in the Simple Math code:

int a = 1; int b = 2;

The keyword int is used to indicate that the compiler should generate a variable of type int. The computer reserves the appropriate amount of memory, and then the user can refer to that chunk of memory as ‘a.’ The value 1 is immediately stored into that memory location.

For example, this code

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

35

produces the following output.

Output:

variable a is 1

Trick Although it isn’t necessary, you can assign a value to a variable as you are creating it, as I did in this program. This ensures that the variable always has a legitimate value. The C# compiler complains if you create a variable that doesn’t have a value assigned. If you prefer, you can simply create a variable without assigning a value, like this: int a; Then assign the value later: a = 1;

Long Integers

At times you need a value larger or smaller than the range of the int. If you need a very large or small integer, you can use the long variable type. A long integer stores its information in 64 digits of binary, so it can handle large (or, of course, small) values. If you need to create a long integer, just use the keyword long, like this:

long a;

If you want to use a long integer as a literal value (for example, assigning a value to a long variable), you use the modifier L at the end of the number, like this:

long a = 21L;

Trap Remember to use a capital L to specify that the value is a long integer. The lowercase l looks a lot like the numeral 1, which can be extremely confusing.

Floating−Point Variables

Like integers, real numbers have multiple kinds of number schemes. Real numbers are those numbers that include decimal values. Computer systems often store real numbers in a floating−point notation, meaning that the decimal point can go anywhere in a number, which gives you a lot of flexibility. Although integers are described by their range (their minimum and maximum values), the most important characteristic of a real number is its precision, the number of significant digits it supports. Floating−point numbers store their values in a form of scientific notation, so they can be extremely large or extremely small. C# uses two main types of real numbers. The float type uses 32 digits of binary and supports a large range. The double type (for the double−precision floating type) uses 64 digits and handles larger values and values extremely close to zero. You probably won’t be surprised to find that you create a floating−point value by using the float keyword, like this:

float myFloat;

You refer to a float value with an f character at the end of the number, like this:

myFloat = 32.4f;

Likewise, you generate a double−precision float with the double keyword:

double myDouble;

You can use the d character to force a number to double status, but doing so is unnecessary because any literal number with a decimal point is presumed to be a double.

36

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