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;
}
第一次看'factorial()'告訴我它總是會返回'0',因爲'int facts = 0;'應該是'int facts = 1;'。然後'main()'運行到一個零除...... – VCSEL
此外'factorial()'中的循環應該以'for(int i = 2; ......'開始,出於同樣的原因 – VCSEL
也,有因式返回一倍,並且宣佈事實是雙重的,這將顯着擴大產生可行因子的「a」的範圍,留給OP的練習以說明在因子()失敗之前「a」有多大。 – doug