How to compute sin and cos together in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>        // Provides std::sin, std::cos, and M_PI if available

// This function receives an angle in radians and computes both sine and cosine.
// Returning them as a std::pair keeps the interface simple and efficient.
std::pair<double, double> computeSinCos(double radians) {
    // Using the standard library's trigonometric functions ensures correctness
    // and leverages optimized implementations provided by the compiler/runtime.
    double s = std::sin(radians);
    double c = std::cos(radians);

    return {s, c};
}

int main() {
    // For demonstration, choose an angle. Here we use 45 degrees converted to radians.
    double degrees = 60.0;

    // Convert degrees to radians using the standard formula.
    double radians = degrees * (M_PI / 180.0);

    // Compute both sine and cosine using our helper function.
    auto result = computeSinCos(radians);

    // Display the results.
    std::cout << "Angle: " << degrees << " degrees\n";
    std::cout << "Radians: " << radians << "\n";
    std::cout << "sin: " << result.first << "\n";
    std::cout << "cos: " << result.second << "\n";
}


/*
run:

Angle: 60 degrees
Radians: 1.0472
sin: 0.866025
cos: 0.5

*/

 



answered Jul 12 by avibootz
...