TU-Programmieren_2/exercise2/task3.cpp
2025-04-09 10:22:44 +02:00

33 lines
1.3 KiB
C++

#include "task3.hpp" // solve_quadratic_equation
#include <valarray>
/// @brief Calculates the real solutions of the quadratic equation a*x^2 + b*x + c = 0.
/// @param a coefficient; assertion: 'a' is a non-zero value
/// @param b coefficient
/// @param c coefficient
/// @return The two real solutions (order: ascending).
/// If no real solutions exists, the tuple contains two quiet NaNs.
std::tuple<double, double> solve_quadratic_equation(double a, double b, double c){
double x1, x2;
double d = b*b - 4*a*c;
if(d < 0){
x1 = NAN;
x2 = NAN;
}else{
x1 = (-b - sqrt(d))/(2*a);
x2 = (-b + sqrt(d))/(2*a);
}
return std::make_tuple(x1, x2);
}
/// @brief Calculates the real solutions of the quadratic equation a*x^2 + b*x + c = 0.
/// @param abc coefficients; assertion: first coefficient 'a' is a non-zero value
/// @return The two real solutions (order: ascending).
/// If no real solutions exists, the tuple contains two quiet NaNs.
std::tuple<double, double> solve_quadratic_equation(std::tuple<double, double, double> abc){
double a = std::get<0>(abc);
double b = std::get<1>(abc);
double c = std::get<2>(abc);
return solve_quadratic_equation(a, b, c);
}