I just started my C++ class yesterday and I'm experiencing some difficulties with accommodating myself to the language. I'm trying to complete a quadratic formula calculator, using five different user-given coefficients (which are then put into arrays), being used to calculate the roots, later placing the smaller roots (from the five equations) into a new array.
What I'm not getting is how to use the coefficients now placed into the arrays to calculate the roots, as well as the calculation for the smaller root. My code so far (I'm only modifying the main function):
#include <iostream>
#include <cmath>
#include <cstdlib>
// True if candidate root is a root of the polynomial a*x*x + b*x + c = 0
bool check_root(int a, int b, int c, float root) {
// plug the value into the formula
float check = a * root * root + b * root + c;
// see if the absolute value is zero (within a small tolerance)
if (fabs(check) > 0.0001) {
std::cerr << "ERROR: " << root << " is not a root of this formula." << std::endl;
return false;
} else {
return true;
}
}
/* Use the quadratic formula to find the two real roots of polynomial. Returns
true if the roots are real, returns false if the roots are imaginary. If the roots
are real, they are returned through the reference parameters root_pos and root_neg. */
bool find_roots(int a, int b, int c, float &root_pos, float &root_neg) {
// compute the quantity under the radical of the quadratic formula
int radical = b*b - 4*a*c;
// if the radical is negative, the roots are imaginary
if (radical < 0) {
std::cerr << "ERROR: Imaginary roots" << std::endl;
return false;
}
float sqrt_radical = sqrt(radical);
// compute the two roots
root_pos = (-b + sqrt_radical) / float(2*a);
root_neg = (-b - sqrt_radical) / float(2*a);
return true;
}
int main() {
int b_array[5];
int c_array[5];
int smaller_root[5];
for (int i=0;i<5;i++){
std::cout << "Enter a 'b' coefficient for the quadratic function: a*x*x + b*x + c = 0" << std::endl;
int b;
std::cin >> b;
b_array[i] = b;
}
for (int i=0;i<5;i++){
std::cout << "Enter a 'c' coefficient for the quadratic function: a*x*x + b*x + c = 0" << std::endl;
int c;
std::cin >> c;
c_array[i] = c;
}
for (int i=0;i<5;i++){
float root_1, root_2;
bool success = find_roots(1,b_array[i],c_array[i], root_1,root_2);
if (root_1>root_2)
smaller_root[i] = root_1;
if (root_2>root_1)
smaller_root[i] = root_2;
} else {
std::cerr << "ERROR: Unable to verify one or both roots." << std::endl;
}
}
return 0;
}
Thank you!