C++ std::cos
In C++, std::cos takes an angle in radians and returns its cosine. In a right triangle, cosine is the adjacent side divided by the hypotenuse.
A simple example
std::cos
- Start with 0 radians
- Do this Find the horizontal component
- Result 1
#include <iostream>
#include <cmath>
int main() {
std::cout << (std::cos(0.0)) << '\n';
}
1
Syntax
std::cos(angle)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonFind the horizontal reach of an awning
A designer is positioning an awning over a window. Relate the length of its arm to the horizontal distance it covers so a drawing can show the reach at a chosen angle.
#include <cmath>
#include <cstdio>
int main() {
const double angle = 1.0471975511965976;
std::printf("%.3f\n", std::cos(angle));
return 0;
}
0.500
At 60 degrees the horizontal reach is half the length of the arm.
Check the reach of a level awning
A builder sketches an awning with its arm completely level. Use that position as a reference when checking the horizontal projection produced by the drawing calculation.
#include <cmath>
#include <cstdio>
int main() {
const double angle = 0.0;
std::printf("%.3f\n", std::cos(angle));
return 0;
}
1.000
A horizontal arm has a horizontal reach equal to its full length.
Find a sign arm’s horizontal reach
A scale model for a shop sign has a 2 m arm raised 30° from horizontal. The artist wants the distance between its tip and the wall along the ground.
Cosine gives the adjacent side as a fraction of the arm length.
What to watch for
The angle is measured from the horizontal and supplied in radians.