[英]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.