Hello! I have the following task: to write in C ++ a method that calculates the GCD for 2 int numbers OR double (template class).

I took the Euclidean algorithm with a few changes:

template <typename T> T rational<T>::nod(T a, T b) { if (a == b) { return a; } if (a > b) { T tmp = a; a = b; b = tmp; } return nod(a, b - a); } 

Works with:

 rational<double> rat(5, 10);//рациональная дробь 5/10 rat.nod(5, 10);//вычисление НОД 5 и 10 

And does not work when:

 rational<double> rat(5.1, 10);//рациональная дробь 5/10 rat.nod(5.1, 10);//вычисление НОД 5.1 и 10 

Question: why is this happening, and how to fix it in order to work in both variants? Thanks in advance for the answers!

  • 3
    What is "not working"? And how should this work? What is the gcd for real numbers in general? What should NOD (5.1, 10) be in your understanding? From this we must begin. - AnT
  • @AnT: The greatest common (integer) divider? Here, apparently, it is 0.1. - VladD
  • And “does not work”, apparently, because 0.1 does not appear to be exactly in the double data type. In particular, checking for equality of double meaningless. - VladD
  • one
    Apparently, you need rational numbers over the ring of integers, that is, rational<int> . - VladD
  • The concept of gcd is defined only on the set of integers. For double there is no such thing, therefore it is impossible to calculate what is not ... Therefore, when using double arguments, the first thing to do is to convert their type to an integer (if necessary, with rounding), to get an integer GCD and convert it back to double . - Akina

0