[英]My function isn't returning anything but does compile and seems correct
很难弄清楚为什么我的代码不返回任何内容。 我希望它返回 '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++;
}
}
}
你需要指定一个返回类型,所以你会有这样的东西。
#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;
}
嗨,您的函数 '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;
}
如果代码编译通过,您应该逐步模拟程序的执行:
main
函数;ft_iterative_factorial
,参数为10
;fact
被初始化为1
;ft_iterative_factorial
,因此丢弃在其范围内声明的所有变量...... ……问题就在这里: fact
的价值丢失了。
如果您希望将该值传递回主函数,您应该例如将函数ft_iterative_factorial
声明为
int ft_iterative_factorial(int nb);
并添加
return fact;
在它的身体末端。
我的函数没有返回任何东西,但可以编译并且看起来是正确的
您的代码根本不正确。 为了检查是否在ft_iterative_factorial
函数中打印了fact
的值。 通过将返回类型从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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.