Csharp/CSharp Tutorial/Operator/Arithmetic Operators

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Arithmetic Operators

C# defines the following arithmetic operators:

Operator Meaning + Addition - Subtraction (also unary minus)

Multiplication / Division % Modulus ++ Increment -- Decrement

When / is applied to an integer, any remainder will be truncated.

For example, 10/3 will equal 3 in integer division.


<source lang="csharp">using System; class MainClass {

   static void Main(string[] args)
   {
       int     a,b,c,d,e,f;
       a = 1;
       b = a + 6;
       Console.WriteLine(b);
       c = b - 3;
       Console.WriteLine(c);
       d = c * 2;
       Console.WriteLine(d);
       e = d / 2;
       Console.WriteLine(e);
       f = e % 2;
       Console.WriteLine(f);
   }

}</source>

Compound operator

<source lang="csharp">using System; public class CompoundAssApp {

   public static void Main(string[] args)
   {
       int nCalc = 10;
       nCalc += 5;
       Console.WriteLine(nCalc);
  
       nCalc -= 3;
       Console.WriteLine(nCalc);
  
       nCalc *= 2;
       Console.WriteLine(nCalc);
  
       nCalc /= 4;
       Console.WriteLine(nCalc);
  
       nCalc %= 4;
       Console.WriteLine(nCalc);
   }

}</source>

postfix and prefix

<source lang="csharp">using System; class MainClass {

 static void Main(string[] args)
 {
   int   a,b,c,d,e,f;
   a = 1;      
   b = a + 1;    
   b = b - 1;    
   c = 1; d = 2;  
   ++c;      
   Console.WriteLine(c);
   --d;      
       Console.WriteLine(d);
       
   e = --c;    
   Console.WriteLine(e);
   f = c--;    
   Console.WriteLine(f);
 }

}</source>

2
1
1
1

shortcut Operators

<source lang="csharp">using System; class MainClass {

 static void Main(string[] args)
 {
   int a, b, c, d, e;
   a = 1;
   a += 1;
   Console.WriteLine(a);
   b = a;
   b -= 2;
   Console.WriteLine(b);
   c = b;
   c *= 3;
   Console.WriteLine(c);
   d = 4;
   d /= 2;
   Console.WriteLine(d);
   e = 23;
   e %= 3;
   Console.WriteLine(e);
 }

}</source>

2
0
0
2
2