void降低();成员函数减少分数

void reduce(); MEMBER FUNCTION REDUCES FRACTIONS

本文关键字:函数 成员 降低 void      更新时间:2023-10-16

这是我需要编写的成员函数。该功能旨在减少分数。void降低((;

这就是我拥有的

void reduce()
{
    num /= gcd();
    den /= gcd();
}

提供了GCD函数,因此不正确。

它不允许我在班级定义的其余部分启动我的代码,因为它太长

我的问题是;为什么我会遇到RELAD((

的错误

我也尝试了

void reduce()
// reduce this fraction to simplest form. For instance,
// 2/4 will be reduced to 1/2
{
    int a = gcd();
    den /= a;
    num /= a;
}

我的代码正在测试以下:

// Test reduce
f1.reduce(); // f1 is -4/5
f2.reduce(); // f2 is 2/3
if(f1.get_numerator() != -4 || f1.get_denominator() != 5 || f2. 
get_numerator() != 2 || f2.get_denominator() != 3)
{
    cout <<"The reduce function was wrong.n";
    result -= 0.5;
}

假设gcd()返回的值取决于numden,因此gcd()在第一行中返回的值将与第二行中gcd()返回的值不同。

gcd()的返回值存储在本地变量中并使用它。

void reduce()
{
    auto g = gcd();
    num /= g;
    den /= g;
}

向您的程序添加一些调试输出:

if ( f1.get_numerator() != -4 ||
     f1.get_denominator() != 5 ||
     f2.get_numerator() != 2 ||
     f2.get_denominator() != 3)
{
   cout <<"The reduce function was wrong.n";
   if ( f1.get_numerator() != -4 )
   {
      cout << "Expected value of f1.get_numerator(): " << -4 << "n";
      cout << "Actual value of f1.get_numerator(): " << f1.get_numerator() << "n";
   }
   else
   {
      cout << "Got the expected value of f1.get_numerator()n";
   }
   if ( f1.get_denominator() != 5 )
   {
      cout << "Expected value of f1.get_denominator(): " << 5 << "n";
      cout << "Actual value of f1.get_denominator(): " << f1.get_denominator() << "n";
   }
   else
   {
      cout << "Got the expected value of f1.get_denominator()n";
   }

   if ( f2.get_numerator() != 2 )
   {
      cout << "Expected value of f2.get_numerator(): " << 2 << "n";
      cout << "Actual value of f2.get_numerator(): " << f2.get_numerator() << "n";
   else
   {
      cout << "Got the expected value of f2.get_numerator()n";
   }
   if ( f2.get_denominator() != 3 )
   {
      cout << "Expected value of f2.get_denominator(): " << 3 << "n";
      cout << "Actual value of f2.get_denominator(): " << f2.get_denominator() << "n";
   }
   else
   {
      cout << "Got the expected value of f2.get_denominator()n";
   }
    result -= 0.5;
}