我正在开发一个程序,该程序应该计算二次函数的根并输出它的根。但是,输出并不是所有情况下都应如此。当它应该没有解决方案或微不足道时,它输出为-nan(ind)
. 当它应该有一个解决方案时,它会输出x1 = -nan(ind)
和x2 = -inf
. 我不太确定为什么会这样,我真的可以使用一些帮助。这是我的代码:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main() {
// Initialize and define the variables:
// a = the variable that stores the value for 'a' in the quadratic
// b = the variable that stores the value for 'b' in the quadratic
// c = the variable that stores the value for 'c' in the quadratic
// d = the variable that stores the determinant of the quadratic function to find the nature of the roots (b^2-4ac)
// root1 = the variable that stores the first possible root of a quadratic function
// root2 = the variable that stores the second possible root of a quadratic function
// realNum = the variable that stores the real portion of the complex roots
// imaginaryNum = the variable that stores the imaginary portion of the complex roots
double a, b, c, d, root1, root2, realNum, imaginaryNum;
// Ask the user to input a value for variable 'a' of the quadratic
// NOTE: 'setprecision' specifies the minimum precision, 'fixed' states a fixed number of decimals will
// appear after the entered digit
cout << "Please input a: " << setprecision(4) << fixed;
cin >> a; /// Store the value in variable 'a'
// Ask the user to input a value for variable 'b' of the quadratic
// NOTE: 'setprecision' specifies the minimum precision, 'fixed' states a fixed number of decimals will
// appear after the entered digit
cout << "Please input b: " << setprecision(4) << fixed;;
cin >> b; /// Store the value in variable 'b'
// Ask the user to input a value for variable 'c' of the quadratic
// NOTE: 'setprecision' specifies the minimum precision, 'fixed' states a fixed number of decimals will
// appear after the entered digit
cout << "Please input c: " << setprecision(4) << fixed;;
cin >> c; /// Store the value in variable 'c'
// Calculate the determinant of the quadratic (b^2 - 2ac)
d = ((pow(b, 2.0)) - (4 * a * c));
// Check to see if the determinant is greater than 0
if (d >= 0) {
// Calculate each of the two possible roots for the quadratic
root1 = (-b + sqrt(d)) / (2 * a);
root2 = (-b - sqrt(d)) / (2 * a);
// Display to the user that a solution does exist for the following quadratic
cout << "Your equation has real roots: " << root1 << " and " << root2 << "." << endl;
}
// Check to see if the determinant is greater than 0
else if (d < 0) {
// Calculate the real portion of the complex roots for the quadratic
realNum = (-b) / (2 * a);
// Calculate the imaginary portion of the complex roots for the quadratic
imaginaryNum = (sqrt(-d)) / (2 * a);
// Combine the two portions of the complex roots and display the calculated complex roots to the user
cout << "Your equation has complex roots: " << realNum << " + " << imaginaryNum << "i and "
<< realNum << " - " << imaginaryNum << "i." << endl;
}
// Indicate that the program ended successfully
return 0;
} // End of function main