使用 C# 中的位運算子將給定的數字乘以 2


可以使用位運算子將數字乘以 2。這是透過使用左移運算子並將位向左移動 1 位來完成的。這將使之前的數字翻倍。

下面提供了一個使用位運算子演示將數字乘以 2 的程式。

示例

 即時演示

using System;
namespace BitwiseDemo {
   class Example {
      static void Main(string[] args) {
         int num = 25, result;
         result = num << 1;
         Console.WriteLine("The original number is: {0}", num);
         Console.WriteLine("The number multiplied by two is: {0}", result);
      }
   }
}

輸出

上述程式的輸出如下。

The original number is: 25
The number multiplied by two is: 50

現在,讓我們瞭解一下上述程式。

首先,定義數字。之後,使用左移運算子,並將 num 中的位向左移動 1 位。這將使之前的數字翻倍,儲存在 result 中。之後,顯示 num 和 result 的值。此程式碼段如下所示 -

int num = 25, result;
result = num << 1;
Console.WriteLine("The original number is: {0}", num);
Console.WriteLine("The number multiplied by two is: {0}", result);

更新日期: 2020-06-27

4K+ 次瀏覽

助你開啟職業生涯

完成課程,獲得認證

開始
廣告