In C++, std::tan(x) calculates the tangent of an angle. In a right triangle, the tangent is the side opposite the angle divided by the side next to it. It is also the slope of a line that rises at that angle.
The angle must be in radians. Unlike sine and cosine, the tangent has no limit: it grows without end as the angle gets close to 90 degrees. It is used in surveying, in graphics, and to find the height of something from a distance.
std::tan() is declared in <cmath> and is part of the group Trigonometry. Trigonometric functions use radians, not degrees. To convert degrees, multiply by std::numbers::pi / 180 (C++20).
Syntax
Include <cmath> and call std::tan. Start with these lines.
C++
double a = std::tan(0.0); // 0
double b = std::tan(std::numbers::pi / 4); // 1 (45 degrees)
float c = std::tan(0.5f); // float version
Call
What it does
std::tan(0.0)
The tangent of 0 radians. Returns 0.
std::tan(std::numbers::pi / 4)
pi / 4 radians is 45 degrees. Returns about 1.
std::tan(35 * std::numbers::pi / 180)
A degree angle after conversion. Returns about 0.700208.
Angles are in radians. Convert degrees with deg * std::numbers::pi / 180. std::numbers::pi needs <numbers> and C++20. With older compilers write const double pi = 3.14159265358979323846; yourself.
Library declarations
C++
float tan(float x);
double tan(double x);
long double tan(long double x);
double tan(Integer x); // for integer types
Parameters
Parameter
Description
x
Required. The angle in radians. It can be float, double, long double, or an integer.
Return Value
Return Value
Description
Tangent
The value of sin(x) / cos(x). It can be any real number.
Very large
Near pi / 2 the result is huge, such as 1.63312e+16, but not inf.
NaN
Returned when x is infinity or NaN.
C++ Examples
Example 1 — Tangent of Common Angles
Convert each angle from degrees to radians, then print the tangent with four decimals.
The tangent is the height divided by the distance on the ground, so multiplying it by 20 gives the height.
At 35 degrees, tan is about 0.7002, so the tree is 14.00 m tall.
A bigger angle means a taller tree: at 50 degrees tan is about 1.1918, giving 23.84 m. This shows how surveyors measure heights.
Frequently Asked Questions
std::tan(x) returns the tangent of the angle x, which is sin(x) divided by cos(x). The angle must be in radians.
The tangent of x as float, double, or long double. Near 90 degrees it becomes a huge number. If x is infinity or NaN, the result is NaN.
In math it is undefined (infinite). In C++ you get a very large number such as 1.63312e+16, because pi / 2 is not exact. It does not return inf. Avoid angles close to 90 degrees.
tan(x) equals sin(x) / cos(x). That is why it gets huge when cos(x) is close to zero, near 90 and 270 degrees.
Include <cmath> and write std::tan(). That always works and picks the C++ overloads. The global name ::tan often works too, but the standard does not promise it, and it may only take a double.