Derek H
Derek H

Reputation: 31

Getting a strange output from computing sin(x)

I am trying to create a program that can compute sin(x) given x and a value n.

I know sin can be computed as:

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

But the output gives me the same number every time: -2147483648.

Here is my code:

#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;
}

Upvotes: 0

Views: 94

Answers (1)

rocambille
rocambille

Reputation: 15956

facts is initialized to 0 in your function factorial, so it is always returning 0. Initialize it to 1. Same goes with your loop starting to 0, multiplying facts with i=0. Try:

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

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

Upvotes: 2

Related Questions