11

I am trying to do a simple trigonometric calculation in C++. The following is an example of the problem I am having with this. As far as I know, C++ works in radians, not degrees. So conversion from radians to degrees should be a simple case of multiplying by 180 and dividing by pi. A simple test is tan(45), which should equate 1. The following program produces a value of 92.8063 however...

#include <iostream>
using namespace std;

#include <math.h>

int main(){
    double a,b;
    a = tan(45);
    b = a * 180 / 3.14159265;
    cout << b;
    return 0;
}

What is wrong?

Matt
  • 251
  • 2
  • 3
  • 6

4 Answers4

14

You're doing it backwards. Don't apply the formula to the output of tan, apply it to the parameter.

Also you'll want to multiply by pi and divide by 180, not vice versa.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
6

The angle is the input to tan. So you want:

a = 45 * 3.141592653589793 / 180.0;
b = tan(a);
cout << b << endl;
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

You must pass radians to the tan function. Also degrees to radian is wrong.

 a = tan(45 * 3.14159265 / 180.);
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
2

Tan accepts an angle, and returns a quotient. It is not the other way around. You want

a = tan(45*3.14159265/180); // Now a is equal to 1.
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384