【VB】【C++】計算n!(階層)

要計算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;
}

專案檔載點(by code::blocks):Xun6 | 4Shared Box.net

在〈【VB】【C++】計算n!(階層)〉中有 8 則留言

  1. 補一個 C 的

    int n_factorial(int n)
    {
    if(n == 1)
    return 1;
    if(n < 1)
    return 0;
    return n * n_factorial(n – 1);
    }

  2. 你的程式有三個問題:

    一、值會溢出。
    二、0!的答案呢?
    三、負數階層呢?

  3. 請問一程式讀入n的值(整數),計算出其!n(n階層)的值。
    註:0!=1,若n<0則不予計算。

    該如何修改呢?
    使用dev c++將上列程式輸入後,程式無法執行?

  4. try in C:

    int n_factorial(int n){
    if (n==0 || n==1){
    return 1;
    }else{
    return n*(n_factorial(n-1);
    }
    }

發佈回覆給「Kane」的留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料