C++ 中的 ratio_equal() 函数及示例
在本文中,我们将讨论 C++ STL 中 ratio_equal() 函数的工作原理、语法和示例。
什么是 ratio_equal 模板?
ratio_equal 模板是 C++ STL 中的内置模板,定义在 <ratio> 头文件中。ratio_equal 用于比较两个比率。此模板接受两个参数,并检查给定的比率是否相等。例如,我们有两个比率 1/2 和 3/6,当我们简化它们时它们是相等的,但数字不相等,因此 C++ 有一个内置模板来检查两个比率是否相等,如果相等则返回 true,否则返回 false。
因此,当我们想要检查两个比率的相等性时,无需在 C++ 中编写完整的逻辑,可以使用提供的模板,这使得编码更容易。
语法
template <class ratio1, class ratio2> ratio_equal;
参数
模板接受以下参数:
ratio1, ratio2 - 这是我们要检查是否相等的两个比率。
返回值
当两个比率相等时,此函数返回 true,否则函数返回 false。
输入
typedef ratio<3, 6> ratio1; typedef ratio<1, 2> ratio2; ratio_equal<ratio1, ratio2>::value;
输出
true
输入
typedef ratio<3, 9> ratio1; typedef ratio<1, 2>ratio2; ratio_equal<ratio1, ratio2>::value;
输出
false
示例
#include <iostream>
#include <ratio>
using namespace std;
int main(){
typedef ratio<2, 5> R_1;
typedef ratio<10, 25> R_2;
//check whether ratios are equal or not
if (ratio_equal<R_1, R_2>::value)
cout<<"Ratio 1 and Ratio 2 are equal";
else
cout<<"Ratio 1 and Ratio 2 aren't equal";
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
Ratio 1 and Ratio 2 are equal
示例
#include <iostream>
#include <ratio>
using namespace std;
int main(){
typedef ratio<2, 5> R_1;
typedef ratio<1, 3> R_2;
//check whether ratios are equal or not
if (ratio_equal<R_1, R_2>::value)
cout<<"Ratio 1 and Ratio 2 are equal";
else
cout<<"Ratio 1 and Ratio 2 aren't equal";
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
Ratio 1 and Ratio 2 aren’t equal
示例
Code-3:
//if we try to enter 0 in the denominator then the output will be
#include <iostream>
#include <ratio>
using namespace std;
int main(){
typedef ratio<2, 5> R_1;
typedef ratio<1, 0> R_2;
//check whether ratios are equal or not
if (ratio_equal<R_1, R_2>::value)
cout<<"Ratio 1 and Ratio 2 are equal";
else
cout<<"Ratio 1 and Ratio 2 aren't equal";
return 0;
}输出
如果我们运行以上代码,它将生成以下输出:
/usr/include/c++/6/ratio:265:7: error: static assertion failed: denominator cannot be zero static_assert(_Den != 0, "denominator cannot be zero");
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP