站内搜索: 请输入搜索关键词
当前页面: 图书首页 > NET For Java Developers Migrating To C#

NET For Java Developers Migrating To C#

[ directory ] Previous Section Next Section

8.1 Arithmetic Operators

Although 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.

Table 8.1. C# Operators

Operator Category

Operators

Arithmetic

+, ? *, /, %

Logical

&&, ||, true, false, !

Bitwise

&, |, ^, ~

String concatenation

+

Increment, decrement

++, --

Shift

>>, <<

Relational

==, <=, >=, <, >, !=

Assignment

=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

Member access

.

Casting

()

Indexing

[]

Conditional

?:

Object creation

new

Type information

is, as, sizeof, typeof

Overflow exception control

checked, unchecked

Pointer-based

*, &, - >, []

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 ] Previous Section Next Section