The cmath library in C++ provides essential mathematical functions, including those for trigonometric calculations like sine and cosine, as well as power and square root operations. Here's a detailed overview of these functions:
Purpose: Computes the sine of an angle given in radians.
Syntax:
double sin(double angle);
Range: The result is in the range [−1,1]
Example:
#include <iostream>
#include <cmath>
int main() {
double angle = M_PI / 3; // 60 degrees in radians
std::cout << "Sine of 60 degrees: " << sin(angle) << std::endl; // Output: 0.866025
return 0;
}
Purpose: Computes the cosine of an angle given in radians.
Syntax:
double cos(double angle);
Range: The result is also in the range [−1,1]
Example:
#include <iostream>
#include <cmath>
int main() {
double angle = M_PI / 3; // 60 degrees in radians
std::cout << "Cosine of 60 degrees: " << cos(angle) << std::endl; // Output: 0.5
return 0;
}
Purpose: Raises a number to the power of another number.
Syntax:
double pow(double base, double exponent);
Example:
#include <iostream>
#include <cmath>
int main() {
double base = 2.0;
double exponent = 3.0;
std::cout << "2 raised to the power of 3: " << pow(base, exponent) << std::endl; // Output: 8
return 0;
}
Purpose: Computes the square root of a number.
Syntax:
double sqrt(double value);
Example:
#include <iostream>
#include <cmath>
int main() {
double value = 16.0;
std::cout << "Square root of 16: " << sqrt(value) << std::endl; // Output: 4
return 0;
}