我的函数没有返回任何内容,但是可以编译并且看起来正确

时间:2018-10-27 09:29:25

标签: c

很难弄清楚为什么我的代码不返回任何内容。我希望它返回“ 3628800”为10! (阶乘)。任何帮助表示赞赏。

#include <stdio.h>

void ft_iterative_factorial(int nb);

int main()
{
    ft_iterative_factorial(10);
    return 0;
}

void ft_iterative_factorial(int nb)
{
    int i;
    int fact;
    int num;

    fact = 1;
    if (num <= 0)
        fact = 1;
    else
    {
        i = 1;
        while (i <= num)
        {
            fact = fact * i;
            i++;
        }
    }
}

4 个答案:

答案 0 :(得分:0)

您需要指定一个返回类型,这样您将获得类似这样的信息。

#include <stdio.h>

int ft_iterative_factorial(int nb);

int main()
{
    int num;
    num = ft_iterative_factorial(10);
    return 0;
}

int ft_iterative_factorial(int nb)
{
    int i;
    int fact;
    int num = nb;

    fact = 1;
    if (num <= 0)
        fact = 1;
    else
    {
        i = 1;
        while (i <= num)
        {
            fact = fact * i;
            i++;
        }
    }

   return fact;
}

答案 1 :(得分:0)

您好,您的函数“ ft_iterative_factorial”没有返回类型。函数应具有返回类型,以将一些值返回给调用函数。 另外,您的阶乘函数中的任何地方都不会使用传递的参数“ nb”。

这是更正的代码:

#include <stdio.h>

//function should have a return value to return something
int ft_iterative_factorial(int nb);

int main()
{
    printf("%d",ft_iterative_factorial(10));
    return 0;
}

int ft_iterative_factorial(int nb)
{
    int i;
    int fact;
    int num = nb;// You have not assigned nb to num
    // In your case num is not initailised

    fact = 1;
    if (num <= 0)
        fact = 1;
    else
    {
        i = 1;
        while (i <= num)
        {
            fact = fact * i;
            i++;
        }
    }
    return fact;
}

答案 2 :(得分:0)

如果代码可以编译,则应逐步模拟程序的执行:

  • 执行进入main函数;
  • 执行以参数ft_iterative_factorial进入10
  • 变量fact初始化为1;
  • [...](算术,这似乎是正确的);
  • 执行离开ft_iterative_factorial,因此丢弃在其范围内声明的所有变量...

...这就是问题所在:fact的值丢失了。

如果您希望将该值传递回主函数,则应将函数ft_iterative_factorial声明为

int ft_iterative_factorial(int nb);

并添加

return fact;

在其主体的末端。

答案 3 :(得分:0)

  

我的函数没有返回任何内容,但确实进行了编译并且看起来   正确

您的代码根本不正确。为了检查,只需在fact函数内打印ft_iterative_factorial的值即可。通过将退货类型从void更改为int,可以解决退货问题,但我认为您应该仔细检查ft_iterative_factorial的正文。

提示::

void ft_iterative_factorial(int nb) //<---change the return type to int
{
    int i;
    int fact;
    int num;

    fact = 1;
    if (num <= 0)  //<-----what is num????? should be nb
        fact = 1;
    else
    {
        i = 1;
        while (i <= num) //<-----what is num????? should be nb
        {
            fact = fact * i;
            i++;
        }
    }
           //<------ just add return statement

}