C 邏輯運算 位運算

2021-05-22 23:44:35 字數 1501 閱讀 7898

c++ gossip: 邏輯運算、位運算

一、邏輯運算

在邏輯上有所謂的「且」、「或」與「反」運算,在c++中也提供這幾個基本邏輯運算所需的「邏輯運算子」(logical operator),分別為「且」(&&)、「或」(||)及「反相」(!)三個運算子。

來看看下面這個程式會輸出什麼?

int num = 75;

cout <<  (num > 70 && num < 80) << endl;

cout << (num > 80 || num < 75) << endl;

cout << !(num > 80 || num < 75) << endl;

三段程式分別會輸出1、0與1,也就是分別表示true、false與true三種狀況。

&&運算中,如果左邊的條件已經被評斷為false,則可立即判斷整個式子為false,因而右邊的條件就不會再評斷; || 運算中如果左邊的條件已經被評斷為true,則可以判斷整個式子為true,因而右邊的式子就不會再判斷。

二、位運算

「位運算子」(bitwise operator),數字設計上有and、or、not、xor與補碼等運算,在c++中提供這些運算的就是位運算子,它們的對應分別是and (&)、or(|)、not(!)、xor(^)與補碼(~)。

如:cout << "and運算:" << endl;

cout << "0 and 0/t/t" << (0 & 0) << endl;

cout << "0 and 1/t/t" << (0 & 1) << endl;

cout << "1 and 0/t/t" << (1 & 0) << endl;

cout << "1 and 1/t/t" << (1 & 1) << endl;

cout << "or運算:" << endl;

cout << "0 or 0/t/t" << (0 | 0) << endl;

cout << "0 or 1/t/t" << (0 | 1) << endl;

cout << "1 or 0/t/t" << (1 | 0) << endl;

cout << "1 or 1/t/t" << (1 | 1) << endl;

cout << "xor運算:" << endl;

cout << "0 xor 0/t/t" << (0 ^ 0) << endl;

cout << "0 xor 1/t/t" << (0 ^ 1) << endl;

cout << "1 xor 0/t/t" << (1 ^ 0) << endl;

cout << "1 xor 1/t/t" << (1 ^ 1) << endl;

cout << "not運算:" << endl;

cout << "not 0/t/t" << (!0) << endl;

cout << "not 1/t/t" << (!1) << endl;

邏輯運算 位運算

今天有人問我,邏輯運算是什麼,現在來解釋一下 邏輯運算就是相當於資訊競賽基礎工具中的一位的位運算 符號對應關係 wedge cap 交 and 與運算 vee cup 並 or 或運算 neg not 非 xor 異或運算 x k 將x的二進位制右移k位 如 x 10110 2 時,k 1,那麼x ...

邏輯位運算與邏輯運算

兩者非常容易混淆,其實這是截然不同的兩種運算.1.邏輯位運算 與運算 1 2 0 0000 0001 0000 0010 0000 0000 0 或運算 1 2 3 0000 0001 0000 0010 0000 0011 3 按位求反 運算,異或 運算略.移位 左移,右移 運算略.2.邏輯運算 ...

邏輯運算和位運算

本文主要針對的是邏輯運算 和位運算 關於移位預算,現在對開發來說基本不用,就不說了。邏輯運算主要是針對多個boolean表示式來說的,即a 1 b 2這種,就是說邏輯運算子左右都是boolean型別的表示式,這裡!是個特例,它是一元運算子,只對右邊boolean表示式取反,即!ture 變成了fal...