代码之家  ›  专栏  ›  技术社区  ›  Celery

C: 函数调用未返回正确值

  •  1
  • Celery  · 技术社区  · 11 年前

    我的函数“欧几里德”正确地计算了预期的返回值(if语句中的f2),但当它从main调用返回时,“gcd=欧几里德(factor_one,factor_two);”不正确。

    示例:以当前的#s作为因子97、13,它应该返回1,这是f2等于的值,但当我打印gcd时,它说它是0。

    我的错误是什么?

    int euclid(int f1, int f2);
    
    int main()
    {
        int factor_one = 97, factor_two = 13;
        int gcd;
        gcd = euclid(factor_one, factor_two);
        //gcd = factor_one % factor_two;
        printf("GCD = %d\n",gcd );
    }
    
    int euclid(int f1, int f2)
    {
       if (f1%f2 == 0)
       {
            //printf("base case %d \n", f2);
            printf("GCD = %d\n",f2 );
            return f2;
       }
       else
       {
           int temp = f1%f2;
           //printf("%d\n", temp);
           euclid(f2, temp);
       }
    }
    
    2 回复  |  直到 11 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    将注释转换为答案。

    1. 您需要从递归调用返回值: return euclid(f2, temp); .

    2. 您可能可以使用 int temp = f1 % f2; 在条件之前;然后 if (temp == 0) { … } else { return euclid(f2, temp); } .

    3. 您应该只打印欧几里德()函数作为调试度量。

    4. 所提出的固定代码中的递归是尾部递归。它可以被迭代替换。

    和 Alan Au 给了圣人 suggestion :

    1. 一般建议:使用 -Wall 。在这种情况下,它会告诉你问题所在: warning: control reaches end of non-void function [-Wreturn-type]

    这些建议产生递归解决方案:

    int euclid(int f1, int f2)
    {
        int temp = f1%f2;
        if (temp == 0)
        {
            //printf("base case %d \n", f2);
            //printf("GCD = %d\n",f2 );
            return f2;
        }
        else
        {
            //printf("%d\n", temp);
            return euclid(f2, temp);
        }
    }
    

    以及迭代解决方案:

    int euclid(int f1, int f2)
    {
        int temp = f1%f2;
        while ((temp = f1 % f2) != 0)
        {
            f1 = f2;
            f2 = temp;
        }
        return f2;
    }
    
        2
  •  0
  •   Binaya    11 年前

    当我在机器中运行代码时,它给出了正确的输出。 正如你所说,我得到的答案是1。 程序正确。检查您使用的编译器。 有些编译器甚至要求返回主函数的值,但很少有编译器不要求。

    最好使用递归函数,因为它将大大减少代码和执行时间。