位置:首頁 > 高級語言 > C#教學 > C#算術運算符

C#算術運算符

下表列出了所有C#支持的算術運算符。假設變量A=10和變量B=20,則:

運算符 描述 示例
+ 兩個操作數相加 A + B = 30
- 兩個操作數相減(第一個減去第二個) A - B = -10
* 兩個操作數相乘 A * B = 200
/ 分子除以分母 B / A = 2
% 模操作,求整除後的餘數 B % A= 0
++ 增量運算符整數值增加一 A++ = 11
-- 增量運算符整數值減去一 A-- = 9

例子

試試下麵的例子就明白了所有的C#提供的算術運算符:

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 21;
            int b = 10;
            int c;

            c = a + b;
            Console.WriteLine("Line 1 - Value of c is {0}", c);
            c = a - b;
            Console.WriteLine("Line 2 - Value of c is {0}", c);
            c = a * b;
            Console.WriteLine("Line 3 - Value of c is {0}", c);
            c = a / b;
            Console.WriteLine("Line 4 - Value of c is {0}", c);
            c = a % b;
            Console.WriteLine("Line 5 - Value of c is {0}", c);
            c = a++;
            Console.WriteLine("Line 6 - Value of c is {0}", c);
            c = a--;
            Console.WriteLine("Line 7 - Value of c is {0}", c);
            Console.ReadLine();
        }
    }
}

讓我們編譯和運行上麵的程序,這將產生以下結果:

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22