要計算n的階層是很簡單的一件事,會寫到這個程式是因為排列組合,我想要精確的知道答案會在幾種左右,因此就寫了n!的函數來幫忙求階層的值,所謂的階層就是指從1*2*3…..*n的意思,而在排列組合中如果要被排列的字有5個字,那麼排列後的結果就最多不超過5*4*3*2*1的值,也就是最多不超過120個答案
以下我把n!做成Function,有VB版的跟C++版的,剛開始學迴圈的人可以用這個函式來學習迴圈的用法,另外因為擔心integer會存不下資料,所以我使用string來傳回資料,到時候用這個Function時要先把傳回值轉成數字型別才可以
VB版n!函式
Function n_factorial(ByVal n As Integer) As String
Dim temp As UInteger = 1
For x = 1 To n
temp *= x
Next
n_factorial = Str(temp)
End Function
專案檔載點(VS2010):Xun6 | 4Shared | Box.net
C++版n!函式
int n_factorial(int n){
int temp=1,x=1;
for(x=1;x<=n;x++){
temp*=x;
}
return temp;
}
把C++丟到這裡看看吧
http://zerojudge.tw/ShowProblem?problemid=a032
蝦毀
這也算是題目!!
補一個 C 的
int n_factorial(int n)
{
if(n == 1)
return 1;
if(n < 1)
return 0;
return n * n_factorial(n – 1);
}
話說標點符號會自動轉碼….
所以你程式碼直接執行會有問題XD
你的程式有三個問題:
一、值會溢出。
二、0!的答案呢?
三、負數階層呢?
這只是一個範例程式
所以我沒想太多xD
請問一程式讀入n的值(整數),計算出其!n(n階層)的值。
註:0!=1,若n<0則不予計算。
該如何修改呢?
使用dev c++將上列程式輸入後,程式無法執行?
try in C:
int n_factorial(int n){
if (n==0 || n==1){
return 1;
}else{
return n*(n_factorial(n-1);
}
}