// 忽略警告
#define _SCL_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <iostream>
#include <boost/integer_traits.hpp> // 类型特性
#include <boost/cstdint.hpp> // 整数类型(如uint16_t)
#include <boost/rational.hpp> // 有理数
using namespace std;
int main()
{
cout << boost::integer_traits<int>::const_max << endl;// 最大值
cout << boost::integer_traits<int>::const_min << endl;// 最小值
cout << boost::integer_traits<int>::is_signed << endl;// 有无符号
cout << boost::integer_traits<bool>::const_max << endl;
cout << boost::integer_traits<bool>::const_min << endl;
cout << (int)boost::integer_traits<char>::const_max << endl;
cout << (int)boost::integer_traits<char>::const_min << endl;
cout << boost::integer_traits<uint16_t>::const_max << endl;
cout << boost::integer_traits<uint16_t>::const_min << endl;
cout << boost::integer_traits<float>::max() << endl;
cout << boost::integer_traits<float>::min() << endl;
uint8_t u8 = 255;
int_fast16_t if16 = 3200;
int_least32_t il32 = if16;
uintmax_t uim = u8 + if16 + il32;
cout << typeid(u8).name() << ":" << sizeof(u8) << endl;
cout << typeid(if16).name() << ":" << sizeof(if16) << endl;
cout << typeid(il32).name() << ":" << sizeof(il32) << endl;
cout << typeid(uim).name() << ":" << sizeof(uim) << endl;
// 有理数
boost::rational<int> a;
boost::rational<int> b(-10);
boost::rational<int> c(31415, 10000);// 已约分
// 分数形式 分子 分母
cout << a << " " << a.numerator() << " " << a.denominator() << endl; // 0/1 0 1
cout << b << " " << b.numerator() << " " << b.denominator() << endl; // 10/1 10 1
cout << c << " " << c.numerator() << " " << c.denominator() << endl; // 6283/2000
cout << boost::rational_cast<double>(c) << endl;// 3.1415
c = 0xF;// 15
cout << c << " " << c.numerator() << " " << c.denominator() << endl; // 15/1
c.assign(100, 20);
cout << c << " " << c.numerator() << " " << c.denominator() << endl; // 5/1
assert(!(c - 5));// !将(c - 5)隐式转换为bool(true)
boost::rational<double> r(13.3);
cout << r << " " << r.numerator() << " " << r.denominator() << endl; // 13.3/1
cout << boost::rational_cast<int>(r) << endl;// 13
// 类型转换
int tb = boost::rational_cast<int>(b);
double tr = boost::rational_cast<int>(r);
try{
boost::rational<int> a1(2,0);// 构造中 发生除0异常
}
catch (boost::bad_rational& e)
{
cout << typeid(e).name() << endl << e.what() << endl;
}
boost::rational<int> a2(8);
boost::rational<int> a3(4);
cout << boost::gcd(a2, a3) << endl;// 最大公约数
cout << boost::lcm(a2, a3) << endl;// 最小公倍数
return 0;
}
来源:CSDN
作者:ztq小天
链接:https://blog.csdn.net/weixin_38850997/article/details/88064185