分数缩短C ++

时间:2013-03-20 16:36:32

标签: c++ function short

我需要缩短分数: 4/5 * 3/4 = 12/20,但我需要缩短它,所以答案必须是:3/5。 我知道我必须使用这个功能:

int NWD(int m1,int m2){
   int d;
   while((m1!=0)&&(m2!=0)){
    if(m1>=m2) m1=m1%m2;
    else m2=m2%m1;
    return d=m1+m2;}
    }

你能帮助我吗?

3 个答案:

答案 0 :(得分:1)

您可以通过将分子和分母除以两者的最大公约数来简化这些分数。计算GCD的常用方法是Euclidean algorithm

答案 1 :(得分:1)

你需要将分子和分母除以两个数字的GCD。

计算GCD int

gcdr ( int a, int b )
{
  if ( a==0 ) return b;
  return gcdr ( b%a, a );
}
礼貌:for GCD code snippet

答案 2 :(得分:0)

这看起来像是你函数的正确版本。

int NWD(int m1,int m2){
   while((m1!=0)&&(m2!=0)){
    if(m1>=m2) m1=m1%m2;
    else m2=m2%m1;
   }
   return m1+m2;
}

int num = 12;
int den = 20;
int d = NWD(num,den);
cout << num/d << '/' << den/d;

未经测试的代码。