0

I'm finding Harmonic numbers, the function cycles through until it finds the correct harmonic number as long as the line I was using to debug the program is input which was the cout line at the end. If I remove any portion of the cout, the program begins to fail again. I am at a complete loss as to how the cout is effecting the program. without it everything stores zeros.

struct fraction
{
  long nume, denom;
};

void add (fraction x, fraction y, fraction& result)
{
  long Numerator, Denominator, GCD, Higher, Lower;
  Numerator = (x.nume * y.denom + x.denom * y.nume);                                                                                       
  Denominator = (x.denom * y.denom);  

if (Numerator > Denominator)
  {
    Lower = Denominator;
    Higher = Numerator;
  }
else if (Numerator < Denominator)
  {
    Higher = Denominator;
    Lower = Numerator;
  }

while (Higher % Lower > 0)
  {                                                                              
    GCD = Higher % Lower;                                                                                                  
    Higher = Lower;                                                                                                 
    Lower = GCD;
  }

result.nume = Numerator/GCD;
result.denom = Denominator/GCD;
cout << "d " << result.nume << "   " << GCD << "   " << Denominator/GCD << " " << result.denom << endl;

}

BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

0

You don't have default values for Higher and Lower so undefined behavior will occur when neither of these two conditions is true:

if (Numerator > Denominator)

... else if (Numerator < Denominator)

I suggest you turn up your compiler warnings so that errors like these are reported. If you're using GCC/Clang turn on "-Wall".

This should be an easy catch when you step thru with the debugger.

kfsone
  • 23,617
  • 2
  • 42
  • 74
  • So I changed Higher and Lower to both equal 0 and got a floating point exception, then I tried 1 and same thing. I then changed Numerator >= Denominator and got a floating point exception as well. – user2749308 Sep 05 '13 at 05:45
  • You should probably flesh out your original post then to form a [simple self-contained compilable example](http://sscce.org/), otherwise this is going to turn into 20 questions. Also, which debugger are you using? – kfsone Sep 05 '13 at 05:48
  • You were right, I just also had to set GCD to equal 1 as well. Thanks for your help. – user2749308 Sep 05 '13 at 05:52
  • No worries - I would recommend that you split the code for reducing the fractions based on GCD into it's own function, reduce, and call that from a simplified version of 'add'. – kfsone Sep 05 '13 at 06:00