Книга: C# 2008 Programmer
Mathematical Operators
Mathematical Operators
C# supports five mathematical operators, shown in the following table.
Operator | Description |
---|---|
+ |
Addition |
- |
Subtraction |
/ |
Division |
* |
Multiplication |
% |
Modulus |
One interesting thing about the division operator (/
) is that when you divide two integers, the fractional part is discarded:
int num1 = 6;
int num2 = 4;
double result = num1 / num2;
Console.WriteLine(result); //---1---
Here both num1
and num2
are integers and hence after the division result only contains the integer portion of the division. To divide correctly, one of the operands must be a noninteger, as the following shows:
int num1 = 6;
double num2 = 4;
double result = num1 / num2;
Console.WriteLine(result); //---1.5---
Alternatively, you can use type casting to force one of the operands to be of type double so that you can divide correctly:
int num1 = 6;
int num2 = 4;
double result = (double)num1 / num2;
Console.WriteLine(result); //---1.5---
The modulus operator (%
) returns the reminder of a division:
int num1 = 6;
int num2 = 4;
int remainder = num1 % num2;
Console.WriteLine(remainder); //---2---
The %
operator is commonly used for testing whether a number is odd or even, like this:
if (num1 % 2 == 0) Console.WriteLine("Even");
else Console.WriteLine("Odd");