Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 8 EXPRESSIONS AND OPERATORS

Simple Arithmetic Operators

The simple arithmetic operators perform the four basic arithmetic operations and are listed in Table 8-6. These operators are binary and left-associative.

Table 8-6. The Simple Arithmetic Operators

Operator

Name

Description

+

Addition

Adds the two operands.

-

Subtraction

Subtracts the second operand from the first.

*

Multiplication

Multiplies the two operands.

/

Division

Divides the first operand by the second. Integer division rounds

 

 

the result toward 0 to the nearest integer.

The arithmetic operators perform the standard arithmetic operations on all the predefined simple arithmetic types.

The following are examples of the simple arithmetic operators:

int x1 = 5 + 6;

double d1

= 5.0

+ 6.0;

int x2

= 12 - 3;

double d2

= 12.0

- 3.0;

int x3

= 3 * 4;

double d3

= 3.0

* 4.0;

int x4

= 10

/ 3;

double d4

= 10.0

/ 3.0;

byte b1 = 5

+ 6;

 

 

 

sbyte sb1 = 6 * 5;

 

 

 

212

CHAPTER 8 EXPRESSIONS AND OPERATORS

The Remainder Operator

The remainder operator (%) divides the first operand by the second operand, ignores the quotient, and returns the remainder. Table 8-7 gives its description.

The remainder operator is binary and left-associative.

Table 8-7. The Remainder Operator

Operator

Name

Description

%

Remainder

Divides the first operand by the second operand and

 

 

returns the remainder

 

 

 

The following lines show examples of the integer remainder operator:

0 % 3 = 0, because 0 divided by 3 is 0 with a remainder of 0.

1 % 3 = 1, because 1 divided by 3 is 0 with a remainder of 1.

2 % 3 = 2, because 2 divided by 3 is 0 with a remainder of 2.

3 % 3 = 0, because 3 divided by 3 is 1 with a remainder of 0.

4 % 3 = 1, because 4 divided by 3 is 1 with a remainder of 1.

The remainder operator can also be used with real numbers to give real remainders.

Console.WriteLine("0.0f % 1.5f is {0}" , 0.0f % 1.5f);

Console.WriteLine("0.5f % 1.5f is {0}" , 0.5f % 1.5f);

Console.WriteLine("1.0f % 1.5f is {0}" , 1.0f % 1.5f);

Console.WriteLine("1.5f % 1.5f is {0}" , 1.5f % 1.5f);

Console.WriteLine("2.0f % 1.5f is {0}" , 2.0f % 1.5f);

Console.WriteLine("2.5f % 1.5f is {0}" , 2.5f % 1.5f);

This code produces the following output:

0.0f

% 1.5f is 0

// 0.0 / 1.5 = 0 remainder 0

0.5f

% 1.5f is 0.5

// 0.5 / 1.5 = 0 remainder .5

1.0f

% 1.5f

is 1

// 1.0

/ 1.5

= 0

remainder 1

1.5f

% 1.5f

is 0

// 1.5

/ 1.5

= 1

remainder 0

2.0f

% 1.5f

is 0.5

// 2.0

/ 1.5

= 1

remainder .5

2.5f

% 1.5f

is 1

// 2.5

/ 1.5

= 1

remainder 1

 

 

 

 

 

 

 

213

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]