Home > Enterprise >  The below code must return 0 because both strings are equal but it display 1 in output?
The below code must return 0 because both strings are equal but it display 1 in output?

Time:04-20

template <typename T>
T GCD(T a, T b) {
    while (b != 0)
    {
        T t = a % b;
        a = b;
        b = t;
    }
    return std::max(a, -a);
}

class Rational {
    
    int x1;
    int y1;
public:
    
    void simplify()
    {
        int m, n,r;
        n = fabs(y1);
        m = fabs(x1);
        while(r = m % n)//Find the Maximum Common Number of m,n
        {
            m = n;
            n = r;
        }
        y1 /= n; // Simplification
        x1 /= n;
        if(y1 < 0) // Convert denominator to positive number
        {
            y1 = -y1;
            x1 = -x1;
        }
    }
    Rational(int num = 0, int denom = 1)
    {
        if (denom) {
            x1 = num;
            y1 = denom;
        }
        else {
            x1 = 0;
            y1 = 1;
        }
    }
    Rational(const Rational& copy)
    {
        x1 = copy.x1;
        y1 = copy.y1;

    }
operator string() const
    {

        int numerator = x1, denominator = y1;
        GCD(numerator, denominator);
        string str;
        if (denominator == 1)
            str = to_string(numerator);
        else
            str = to_string(numerator)   "/"   to_string(denominator);
        return str;


    }
int main()
{
    Rational a(2, 8);
    string expected1 = "1/4";
    string actual1 = (string)a;
    cout<<actual1.compare(expected1);


}

I am trying to run this program on visual studio. In the main function this code must give 0 in output if we compare actual1 and expected1 because both string are equal but when I run this program I am getting 1 in output I don't know why. Kindly check and let me know where I am wrong. In main function I have declared one object of rational class which when we simplify gives 1/4 as expected value.

CodePudding user response:

Just a guess, would it be to do with the fact that you aren't using the result of GCD when converting to the string?

          int numerator = x1, denominator = y1;
-         GCD(numerator, denominator);
          int gcd = GCD(numerator, denominator);
          numerator /= gcd;
          denominator /= gcd;
          string str;
  • Related