C++分数的表达,C++的<ratio>头文件

自从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;
}


  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值