In C++, std::cos(x) calculates the cosine of an angle. In a right triangle, the cosine is the side next to the angle divided by the long side (hypotenuse). It always gives a value from -1 to 1.
Like std::sin(), the angle must be in radians. The cosine of 0 is 1, it falls to 0 at a quarter turn, and it reaches -1 at a half turn. It is used to find the horizontal part of a movement and to rotate points.
std::cos() 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::cos. Start with these lines.
C++
double a = std::cos(0.0); // 1
double b = std::cos(std::numbers::pi); // -1 (180 degrees)
float c = std::cos(0.5f); // float version
Call
What it does
std::cos(0.0)
The cosine of 0 radians. Returns 1.
std::cos(std::numbers::pi / 3)
pi / 3 radians is 60 degrees. Returns about 0.5.
std::cos(180 * std::numbers::pi / 180)
A degree angle after conversion. Returns -1.
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 cos(float x);
double cos(double x);
long double cos(long double x);
double cos(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
Cosine
A value between -1 and 1 for the angle x.
NaN
Returned when x is infinity or NaN.
1
cos(0.0) and cos(-0.0) both return exactly 1.
C++ Examples
Example 1 — Cosine of Common Angles
Convert each angle from degrees to radians, then print the cosine with four decimals.
0 degrees: covers 10.00 m
30 degrees: covers 8.66 m
60 degrees: covers 5.00 m
How It Works
The cosine is the ground distance divided by the length, so multiplying the cosine by 10 gives the ground distance.
A flat ramp at 0 degrees covers the full 10.00 m. At 30 degrees it covers 8.66 m.
At 60 degrees the ramp is steep and covers only 5.00 m along the ground. Compare this with the height from sin().
Frequently Asked Questions
std::cos(x) returns the cosine of the angle x. The angle must be in radians, not degrees. The result is always between -1 and 1.
The cosine of x as float, double, or long double, a value from -1 to 1. If x is infinity or NaN, the result is NaN.
They are the same wave shifted by a quarter turn. In a right triangle, sin is opposite over hypotenuse and cos is adjacent over hypotenuse. cos(0) is 1, while sin(0) is 0.
A double cannot hold pi exactly, so the angle is slightly off and cos returns about 6.12323e-17. Compare with a small tolerance and do not use ==.
Include <cmath> and write std::cos(). That always works and picks the C++ overloads. The global name ::cos often works too, but the standard does not promise it, and it may only take a double.