C:函数调用没有返回正确的值

时间:2015-08-17 03:36:46

标签: c function return return-value

我的功能" euclid"正确计算预期的返回值(if语句中的f2),但是当它从main中的调用返回时," gcd = euclid(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 个答案:

答案 0 :(得分:2)

将评论转换为答案。

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

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

  3. 您应该只在euclid()函数中打印作为调试措施。

  4. 建议的固定代码中的递归是尾递归。它可以被迭代替换。

  5. Alan Au给了圣人suggestion

      
        
    1. 一般建议:使用-Wall打开编译器警告总是一个好主意。在这种情况下它会告诉你这个问题:warning: control reaches end of non-void function [-Wreturn-type]
    2.   

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

    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;
    }
    

答案 1 :(得分:0)

当我在我的机器中运行代码时,它给出了正确的输出。 正如你所说,答案我得到了1。 该计划是正确的。检查您使用的编译器。 有些编译器要求为main函数返回值,很少有人不要问。

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