大家好,我是Ace,这篇文章是《离散数学及其应用》第一章 计算机课题的源码,希望大家喜欢。
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; }