| [ directory ] |
|
8.1 Arithmetic OperatorsAlthough arithmetic operators are traditionally used on numeric data types, they can also be used in the context of other nonnumeric data types. The following discussion assumes that we are dealing with numeric data types. We discuss the meaning of these operators in nonnumeric contexts in Section 8.18. The +, -, /, *, and % operators have the same meaning in C# as they have in Java. In the context of two numeric operands the +, -, /, *, and % operators add, subtract (the right-hand side [RHS] operand from the left-hand side [LHS] operand), divide (the LHS operand by the RHS), multiply the two operands, and calculate the remainder of dividing the LHS operand by the RHS. Listing 8.1 shows these operators in action.
Listing 8.1 C# Math Operators
using System;
public class MathOperators {
public static void Main(string[] args)!! {
int x = 4;
int y = 2;
float z = 4.0f;
//Int and Int
Console.WriteLine(" x = 4, y = 4");
Console.WriteLine("x+y {0}", x+y);
Console.WriteLine("x-y {0}", x-y);
Console.WriteLine("x*y {0}", x*y);
Console.WriteLine("x/y {0}", x/y);
Console.WriteLine("x%y {0}", x%y);
//Int and Float
Console.WriteLine("\n y = 2, z = 4.0f");
Console.WriteLine("z+y "+(z+y)+" Type="+(z+y).GetType());
Console.WriteLine("z-y "+(z-y)+" Type="+(z-y).GetType());
Console.WriteLine("z*y "+(z*y)+" Type="+(z*y).GetType());
Console.WriteLine("z/y "+(z/y)+" Type="+(z/y).GetType());
Console.WriteLine("z%y "+(z%y)+" Type="+(z%y).GetType());
}
}
The output of Listing 8.1 is as follows: x = 4, y = 4 x+y 6 x-y 2 x*y 8 x/y 2 x%y 0 y = 2, z = 4.0fz+y 6 Type=System.Single z-y 2 Type=System.Single z*y 8 Type=System.Single z/y 2 Type=System.Single z%y 0 Type=System.Single Listing 8.1 uses the arithmetic operators on mixed data types (int and float). The results look identical to those of conducting the operations with two integers. To differentiate between the results, we print the Type of the result in the second batch. Note that when you mix types, the expression is evaluated as the larger data type. |
| [ directory ] |
|