C# 中的數字


對於 C# 中的數字,使用型別 int。它表示一個整數,即正或負整數。

讓我們看看如何使用數學運算子 + − 在 C# 中新增兩個整數。

using System;
using System.Linq;

class Program {
   static void Main() {
      int x = 20;
      int y = 30;
      int sum = 0;

      sum = x + y;
      Console.WriteLine(sum);
   }
}

現在讓我們瞭解這些數學運算子的順序,即運算子優先順序。

運算子優先順序確定表示式中各項的分組。這會影響表示式的求值。某些運算子的優先順序高於其他運算子;例如,乘法運算子的優先順序高於加法運算子。

例如 x = 9 + 2 * 5;此處,向 x 分配 19,而不是 55,因為運算子 * 的優先順序高於 +,因此第一個求值為 2*5,然後向其新增 9。

以下是顯示運算子順序的一個示例 −

示例

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         int a = 200;
         int b = 100;
         int c = 150;
         int d = 50;
         int res;

         res = (a + b) * c / d;
         Console.WriteLine("Value of (a + b) * c / d is : {0}", res);

         res = ((a + b) * c) / d;
         Console.WriteLine("Value of ((a + b) * c) / d is : {0}", res);

         res = (a + b) * (c / d);
         Console.WriteLine("Value of (a + b) * (c / d) : {0}",res);

         res = a + (b * c) / d;
         Console.WriteLine("Value of a + (b * c) / d : {0}",res);

         Console.ReadLine();
      }
   }
}

更新於: 2020 年 6 月 21 日

200 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.