1

这是一个简单的任务,但我似乎无法弄清楚如何去做

这是一个示例函数结构

private double GetGCD(double num1, double num2)
{
    //should return the GCD of the two double
}

测试数据

   num1 = 6;
   num2 = 3;
   *return value must be 3*

   num1 = 8.8;
   num2 = 6.6;
   *return value must be 2.2*

   num1 = 5.1;
   num2 = 8.5;
   *return value must be 1.7*

注意:最大小数位数为 1。编程语言并不重要。我只需要算法

请帮忙..谢谢!

4

6 回答 6

4

如果您只有一位小数,请将数字乘以 10,将它们转换为整数并运行整数 GCD 函数

这也将为您节省浮点精度错误

引用这个答案,Python中的基本欧几里得算法(对于整数!)是:

def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

所以,你的代码应该是这样的:

 def gcd_floats(x,y):
     return gcd( int(x*10), int(y*10) )/10
于 2012-02-22T09:27:28.053 回答
3

当它是 8.8 和 6.6 时,您可以找到 88 和 66 的 GCD,然后将其除以 10。

于 2012-02-22T09:29:23.067 回答
1

网络上有无数地方可以找到 GCD 函数的代码。因为,严格来说,它只定义在整数上,我建议你将你的双精度数乘以 10,计算出 GCD 并将结果除以 10。这将为你避免因使用错误的数据类型而引起的痛苦。

于 2012-02-22T09:28:56.727 回答
1

这是来自谷歌的一些 java 代码的来源:http ://www.merriampark.com/gcd.htm这是相当全面的。

于 2012-02-22T09:29:13.983 回答
1

不存在非离散数的 GCD 之类的东西。但是,您的情况更具体。如果您的输入不是双精度数,而是小数,那么您可以将其转换为分数,将分母相乘,找到分子的 GCD,然后再除以。那是:

8.800 = 8800/1000 = 44/5 (by GCD)
6.600 = 6600/1000 = 33/5 (by GCD)

5.100 = 5100/1000 = 51/10
8.500 = 8500/1000 = 17/2

在这一步中简化分数是很有用的,以避免我们的数字变得太大。

移到一个共同点:

44*5/5*5 = 220/25
33*5/5*5 = 165/25

51*2/2*10 = 102/20
17*10/2*10 = 170/20

分子的 GCD:

gcd(165,220) = 55

gcd(102,170) = 34

所以答案是 55/25 和 34/20。

于 2012-02-22T09:43:09.577 回答
0

使用2种方法

  1. 传统的划分方法
  2. 欧几里得方法

    class GCD
    {
        public static void main(String[] args)
        {
            int a = (int)(1.2*10);
            int b = (int)(3.4*10);

            System.out.println((float)gcd(a, b)/10);
        }
    // 1

        public static int gcd(int a, int b)
        {
            if(b==0)
                return a;
            else
                return gcd(b, (int)a%b);
        }

    // 2
        public static int gcd(int a, int b)
        {
            int k,i;

            if(a>b)
                k = b;
            else
                k = a;

            for(i=k; i>=2; i--)
            {
                if( (a%i==0)&&(b%i==0) )
                {
                    break;
                }
            }
            return i;
        }
    }
于 2012-02-22T09:40:05.387 回答