《離散數學及其應用》第一章 計算機課題

《離散數學及其應用》第一章 計算機課題

來自專欄《離散數學及其應用》計算機課題源碼1 人贊了文章

C++實現:

1.

#include <iostream>using std::cin;using std::cout;using std::boolalpha;using std::endl;int main(){ bool truthP = false, truthQ = false; // 定義變數存儲命題p和q的真值,並且初始化。 cout << "Please enter truth of p and q:" << endl; cin >> truthP >> truthQ; cout << boolalpha; // 開啟以布爾值輸出bool類型變數的模式 cout << "AND: " << (truthP && truthQ) << endl; cout << "OR : " << (truthP || truthQ) << endl; cout << "XOR: " << static_cast<bool>(truthP ^ truthQ) << endl; // 由於C++中只有按位異或,結果是一個整型,因此轉換為bool類型變數以便輸出 cout << "p->q: " << !(truthP && !truthQ) << endl; // 只有當前提真,結果假時,條件語句才為假 cout << "p<->q: " << !(truthP ^ truthQ) << endl; // 雙條件語句即為同或,即為異或的非 return 0;}

2.

#include <iostream>#include <bitset>#include <cstdint>using std::cin;using std::cout;using std::endl;using std::bitset;// 由於std::bitset類模板構造時需要指定其長度,因此使用函數模板的非類型參數來構造中間的std::bieset變數。template<size_t N>inline bitset<N> BitSetAnd(bitset<N> bitsetLeft, bitset<N> bitsetRight){ bitset<N> bitsetAnd; for (size_t pos = 0; pos != N; ++pos) bitsetAnd.set(pos, bitsetLeft[pos] && bitsetRight[pos]); return bitsetAnd;}template<size_t N>inline bitset<N> BitSetOr(bitset<N> bitsetLeft, bitset<N> bitsetRight){ bitset<N> bitsetOr; for (size_t pos = 0; pos != N; ++pos) bitsetOr.set(pos, bitsetLeft[pos] || bitsetRight[pos]); return bitsetOr;}template<size_t N>inline bitset<N> BitSetXor(bitset<N> bitsetLeft, bitset<N> bitsetRight){ bitset<N> bitsetXor; for (size_t pos = 0; pos != N; ++pos) bitsetXor.set(pos, static_cast<bool>(bitsetLeft[pos] ^ bitsetRight[pos])); return bitsetXor;}int main(){ const uint32_t n = 64; // 設定位串的長度為64 bitset<n> bitsetA("101011"), bitsetB("010101"); // 通過std::string初始化兩個std::bitset便於比較 cout << BitSetAnd(bitsetA, bitsetB) << endl; cout << BitSetOr(bitsetA, bitsetB) << endl; cout << BitSetXor(bitsetA, bitsetB) << endl; return 0;}

4.

#include <iostream>#include <cstdint>using std::cin;using std::cout;using std::endl;int main(){ double p = 0, q = 0; cout << "請輸入p和q(p和q的取值範圍在0到1之間,中間請用空格隔開):" << endl; cin >> p >> q; if (p > 1 || q > 1 || p < 0 || q < 0) { cout << "輸入有誤!" << endl; return -1; } cout << "模糊邏輯合取:" << (p < q ? p : q) << endl; cout << "模糊邏輯析取:" << (p > q ? p : q) << endl; return 0;}

第一次發文章,歡迎大家一起來對答案,一起學習!

推薦閱讀:

TAG:離散數學 | 計算機科學 | 離散數學及其應用書籍 |