2017-04-01 19 views
-4

這是一個簡單的因子計算器。我用三個不同的參數調用函數factorial來測試它。出於某種原因,該功能不返回預期值:定製析因函數不按預期工作

#include <iostream> 
using namespace std; 

int factorial(int a) { 
    int result = 1; 
    for (int i = 0; i < a; i++) { 
    result *= result + 1; 
    } 
    return result; 
} 

int main() { 
    cout << factorial(4) << endl; // returns 1806, expected 24 
    cout << factorial(5) << endl; // returns 3263442, expected 120 
    cout << factorial(6) << endl; // returns -1461943274, expected 720 
    return 0; 
} 
+2

階乘的定義是什麼?顯然,你不太熟悉它。 – ForceBru

+0

也許你可以試着在紙上寫下你的程序爲你的一些輸入做什麼。 (不一定是紙張,關鍵是要像你的程序一樣一步一步來) – TGar

+0

並使用你的調試器。這比張貼在這裏更快。 –

回答

1

的問題是在你的階乘的功能,正在添加1個爲什麼?你應該開始從i=1你的循環,以i<=a繁衍i代替+1

通過數學定義Factorial of n = n*(n-1)*(n-2)...3.2.1

您可以修改這樣

int factorial(int a) { 
    int result = 1; 
    for (int i = 1; i <=a; i++) { 
     result = result * i; 
    } 
    return result; 
} 

你的代碼或者你可以使用遞歸函數

int factorial(int a) { 
    if (a == 1) 
     return 1; 
    else 
     return a * factorial(a - 1); 
} 
1

我會用一個while循環在你的函數,而不是一個for循環:

int factorial(int a) 
{ 
    int result = 1; 
    while (a > 0) 
    { 
     result *= a; 
     a--; 
    } 
    return result; 
} 

編輯: 一個問題與您的代碼是,你不但沒有減少我在你的for循環:應該是這樣的:

int factorial(int a) { 
    int result = 1; 
    for (int i = a; i > 0; i--) 
    } 
    result *= i; 
    return result; 
}