自从C++11以后C++的标准库提供了ratio模板类,它提供了一些分数的基本操作,并且能够减少溢出的可能性,并且能够自动去除除零错误。该类定义在ratio头文件下。
该模板的主要构成为:
template<intmax_t N, intmax_t D = 1> class ratio{
public:
typedef ratio<num, den> type;
static constexpr intmax_t num;
static constexpr intmax_t den;
};
其中关键字constexpr是C++11引入的新的关键字,表示该变量是在编译时计算的。
其中num代表分子,den代表分母,constexpr修饰符表示这个变量是在编译时计算的。intmax_t是在头文件<cstdint>的用64比特表示的类型。
vs2013中表示如下(分子分母都除以了最大公约数,而且提取了符号,并且声明了一些断言。):
template<intmax_t _Nx,
intmax_t _Dx = 1>
struct ratio
{ // holds the ratio of _Nx to _Dx
static_assert(_Dx != 0,
"zero denominator");
static_assert(-INTMAX_MAX <= _Nx,
"numerator too negative");
static_assert(-INTMAX_MAX <= _Dx,
"denominator too negative");
static const intmax_t num = _Sign_of<_Nx>::value * _Sign_of<_Dx>::value
* _Abs<_Nx>::value / _Gcd<_Nx, _Dx>::value;
static const intmax_t den = _Abs<_Dx>::value / _Gcd<_Nx, _Dx>::value;
typedef ratio<num, den> type;
};
下面是ratio的一些常用的操作:
ratio中预定义了一些ratio Units方便使用:
具体用法:
#include "stdafx.h"
#include <iostream>
#include <ratio>
using namespace std;
int main()
{
ratio<2, 10> TwoDTen;
cout << TwoDTen.num << "/" << TwoDTen.den << endl; //第一种用法
typedef ratio<5, 3> FiveDThierds;
cout << FiveDThierds::num << "/" << FiveDThierds::den << endl; //第二种用法
cout << ratio_add<ratio<2, 10>, FiveDThierds>::num << "/" << ratio_add<ratio<2, 10>, FiveDThierds>::den << endl;//加法
cout << boolalpha;
cout << is_same<kilo, ratio<1000, 1>>::value << endl;
return 0;
}