2016-11-24 82 views
0

我想創建一個程序,可以計算sin(x)給出x和值n從計算罪(x)得到一個奇怪的輸出

我知道罪可以計算爲:

x - x3/3! + x5/5! - x7/7! + x9/9!... 

但產量使我有同樣數量的每一次:-2147483648

這裏是我的代碼:

#include <iostream> 
#include <cmath> 
using namespace std; 

int factorial(int); 

int main() { 

    int ans = 0; 
    double x = 0; 
    int n = 0; 

    cout << "Enter x value: "; 
    cin >> x; 
    x = x * (3.14159/180); 
    cout << endl; 
    cout << "Enter n value: "; 
    cin >> n; 

    ans = pow(x, 1 + (2 * n))/factorial(1 + (2 * n)); 

    cout << ans << endl; 

    return 0; 
} 

int factorial(int a) { 
    int facts = 0; 

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

第一次看'factorial()'告訴我它總是會返回'0',因爲'int facts = 0;'應該是'int facts = 1;'。然後'main()'運行到一個零除...... – VCSEL

+0

此外'factorial()'中的循環應該以'for(int i = 2; ......'開始,出於同樣的原因 – VCSEL

+0

也,有因式返回一倍,並且宣佈事實是雙重的,這將顯着擴大產生可行因子的「a」的範圍,留給OP的練習以說明在因子()失敗之前「a」有多大。 – doug

回答

2

facts在你的函數factorial初始化爲0,所以它總是返回0。它初始化爲1。同去與你的循環開始爲0,則乘以factsi=0。嘗試:

int factorial(int a) { 
    int facts = 1; 

    for (int i = 2; i <= a; i++) { 
     facts *= i; 
    } 
    return facts; 
}