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