A. Cervantes
A. Cervantes

Reputation: 27

Math expression with cos() not returning expected value

I'm trying to use cosine and sine, however they do not return the value I'm expecting.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main() {
    float magnitudeForce;
    int force;

    float theta;
    float angle;
    double x;
    double y;
    int i = 0;

    while(i < 3){
        printf("Please enter the value of the force"
            " and the angle from the x-axis of the force:\n");
        scanf("%d %f", &force, &angle);
        printf("The force and the angle are: %d %.2lf.\n", force, angle);

        x = force * cos(angle);
        printf("%lf\n", x);

        ++i;
    }
    return 0;
}

So if the force is 8 and the angle 60 then the return should be 4, but it is returning -7.62.

Upvotes: 0

Views: 115

Answers (1)

paxdiablo
paxdiablo

Reputation: 881453

The C cos function requires its argument to be in radians rather than degrees.

While the cosine of sixty degrees is 0.5, the cosine of 60 radians is about -0.95, which is why you're seeing -7.62 when you multiply it by eight.

You can fix this by doing something like:

x = force * cos(angle * M_PI / 180.0);

Keep in mind that M_PI is a POSIX thing rather than an ISO thing so it may not necessarily be in your C implementation. If it's not, you can just define it yourself with something like:

const double M_PI = 3.14159265358979323846264338327950288;

Upvotes: 5

Related Questions