code.club

 找回密碼
 立即註冊
搜索
查看: 5887|回復: 0
打印 上一主題 下一主題

階乘數解法一問

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2015-1-8 19:56:58 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
本帖最後由 enter 於 2015-1-8 19:58 編輯

這問題是要寫一個可以輸入一數字之後,可以階乘的函數,例如輸入6,就會算出1*2*3*4*5*6=720。

我的寫法如下:
#include <stdio.h>

int fact(int i);

int main(void)
{
int x;
printf("enter a number:\n");
scanf("%d",&x);
printf("%d",fact(x));

return 0;
}

int fact(int i)
{

if(i>1) i=i*fact(i-1);
return i;
}

而書上解答則是:

#include <stdio.h>

int fact(int i);

int main(void)
{
int x;
printf("enter a number:\n");
scanf("%d",&x);
printf("%d",fact(x));
return 0;
}

int fact(int i)
{
if(i==1) return 1;
else return i*fact(i-1);
}

二者答案都對,但不知我上面的寫法是否有什麼隱藏問題呢?

謝謝。
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-4-20 22:25 , Processed in 0.079081 second(s), 19 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表