0

以下のプログラムは 2 つの数値の LCM を計算します。予想される出力は 54 と 24 の入力で 216 ですが、57 になります。

誰かが同じことを手伝ってくれますか。以下のコード スニペットの何が問題なのか教えてください。

/* *********** /
*** LCM ******/
/**************/
template<bool cond, int V1, int V2>
struct IfCond
{
    enum
    {
        value = V1
    };
};

template<int V1, int V2>
struct IfCond<0, V1, V2>
{
    enum
    {
        value = V2
    };
};

template<int V1, int V2>
struct findMax
{
    enum
    {
        result = V1 > V2,
        value = IfCond<result, V1, V2>::value
    };
};

template<int V1, int V2, int max>
struct findLCM
{
    enum
    {
        result = findLCM<max % V1, max % V2, max+1>::result
    };
};

template<int V2, int max>
struct findLCM<0, V2, max>
{
    enum
    {
        result = findLCM<0, max % V2, max+1>::result
    };
};

template<int V1, int max>
struct findLCM<V1, 0, max>
{
    enum
    {
        result = findLCM<max % V1, 0, max+1>::result
    };
};

template<int max>
struct findLCM<0, 0, max>
{
    enum
    {
        result = max
    };
};

int main()
{
    std::cout<< findLCM<54, 24, findMax<54, 24>::value>::result << std::endl;
}
4

3 に答える 3

0

私はあなたがこのようなことをすることができると思います

#include <iostream>

template <int X, int Y>
struct findGDMH
 { static int const result = findGDMH<Y, X%Y>::result; };

template <int X>
struct findGDMH<X, 0>
 { static int const result = X; };

template <int X, int Y>
struct findGDM
 {
   static bool const largerIsX = (X > Y);
   static int  const A         = (largerIsX ? X : Y);
   static int  const B         = (largerIsX ? Y : X);
   static int  const result    = findGDMH<A, B>::result;
 };

template <int X>
struct findABS
 { static int const  result = (X > 0 ? X : -X); };

template <int X, int Y>
struct findLCM
 { static int const  result = findABS<X*Y>::result
   / findGDM<findABS<X>::result, findABS<Y>::result>::result; };

template <int X>
struct findLCM<X, 0>
 { static int const  result = 0; };

template <int X>
struct findLCM<0, X>
 { static int const  result = 0; };

template <>
struct findLCM<0, 0>
 { static int const  result = 0; };


int main() 
{
    std::cout<< findLCM<54, 24>::result << std::endl;

    return 0;
}
于 2016-03-29T09:13:02.843 に答える