C++ 中的 ratio_not_equal() 及其示例


在本文中,我们将讨论 C++ STL 中 ratio_not_equal 模板的工作原理、语法和示例。

什么是 ratio_not_equal 模板?

ratio_not_equal 模板是 C++ STL 中内置的,定义在 <ratio> 头文件中。ratio_not_equal 用于比较不相等的两个比率。此模板接受两个参数并检查给定的比率是否不应相等。比如我们有两个比率 1/2 和 3/9,它们不相等,因此对于给定的模板,它们成立。当两个比率不相等时,此函数返回 true。

因此,当我们想检查两个比率是否不等时,可以利用提供的模板(简化了编码)代替用 C++ 编写整个逻辑。

语法

template <class ratio1, class ratio2> ratio_not_equal;

参数

该模板接受以下参数 −

  • ratio1, ratio2 − 这是我们想要检查它们是否相等的两个比率。

返回值

当两个比率不相等时,此函数返回 true,否则,当两个比率相等时,此函数返回 false。

输入 

typedef ratio<3, 6> ratio1;
typedef ratio<1, 2> ratio2;
ratio_not_equal<ratio1, ratio2>::value;

输出

false

输入 

typedef ratio<3, 9> ratio1;
typedef ratio<1, 2> ratio2;
ratio_not_equal<ratio1, ratio2>::value;

输出 

true

示例

 实时演示

#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_not_equal<R_1, R_2>::value)
      cout<<"Ratio 1 and Ratio 2 aren't equal";
   else
      cout<<"Ratio 1 and Ratio 2 are equal";
   return 0;
}

输出

如果我们运行上面的代码,他会生成如下的输出 −

Ratio 1 and Ratio 2 aren't equal

示例

 实时演示

#include <iostream>
#include <ratio>
using namespace std;
int main(){
   typedef ratio<2, 5> R_1;
   typedef ratio<2, 5> R_2;
   //check whether ratios are equal or not
   if (ratio_not_equal<R_1, R_2>::value)
      cout<<"Ratio 1 and Ratio 2 aren't equal";
   else
      cout<<"Ratio 1 and Ratio 2 are equal";
   return 0;
}

输出

如果我们运行上面的代码,他会生成如下的输出 −

Ratio 1 and Ratio 2 aren equal

更新于: 22-4-2020

88 次浏览

开启您的 职业生涯

通过完成本课程认证

开始
广告
© . All rights reserved.