holyya.com
2025-09-04 08:52:52 Thursday
登录
文章检索 我的文章 写文章
如何用C++判断两个分数是否相等?
2023-07-05 16:37:05 深夜i     --     --
C++ 分数 判断 相等

在C++中,判断两个分数是否相等可以通过比较它们的分子和分母是否相等来实现。具体实现方法如下:

1. 定义一个分数类Fraction,其中分别存储分子和分母的值。

2. 重载“==”操作符,用于判断两个分数是否相等。

3. 在“==”操作符中,分别比较两个分数对象的分子和分母是否相等,如果相等则返回true,否则返回false。

下面是一份示例代码:


#include <iostream>

using namespace std;

class Fraction {

public:

  int numerator;  // 分子

  int denominator; // 分母

  Fraction(int num, int den)

    numerator = num;

    denominator = den;

  

  bool operator==(const Fraction& other) const

    return numerator == other.numerator && denominator == other.denominator;

  

};

int main() {

  Fraction f1(1, 2);

  Fraction f2(2, 3);

  Fraction f3(4, 8);

  if (f1 == f2)

    cout << "f1 and f2 are equal" << endl;

   else

    cout << "f1 and f2 are not equal" << endl;

  

  if (f1 == f3)

    cout << "f1 and f3 are equal" << endl;

   else

    cout << "f1 and f3 are not equal" << endl;

  

  return 0;

}

输出结果如下:


f1 and f2 are not equal

f1 and f3 are equal

以上就是使用C++判断两个分数是否相等的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复