Public Group

This topic is 1746 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi, about a week ago I made a program that calculated quadratic formulas. Now, I'm supposed to change that program and use a function to the calculations. Problem is, it prints both x1 and x2 as "-1.#IND".

I've googled around and apparently it happens when you divide by zero, but a isn't 0.

#include "../../std_lib_facilities.h"

void quadratic(double a, double b, double c){ // Calculate and print x
double x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 *a);
cout << "X1 == " << x1 << endl;
double x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 *a);
cout << "X2 == " << x2 << endl;
}

int main()
{
double a = 1, b = 1, c = 1;	// Input loop
cout << "This program will help you solve ax (squared) + bx + c = 0\nEnter a, b and c\n";
while (cin >> a && cin >> b && cin >> c)
}


Share on other sites

It can also happen if you take the square root of a negative number, which happens if your polynomial doesn't have any real roots.

Share on other sites

Also if a may be zero (straight line), then you need to handle that because the "/ (2 * a)" becomes divide by zero.

Share on other sites

Ah, thanks, I just had to make sure b*b > 4(ac).

Share on other sites

The more usual way would be to just take the contents of sqrt, calculate it and check it for negative.

assert(a != 0);//if may be true, do something about it
double d = b * b - 4 * a * c;
if (d < 0)
{
return; //no root
}

double dSqrt = std::sqrt(d);

double x1 = (-b + dSqrt) / (2 * a);
double x2 = (-b - dSqrt) / (2 * a);

Edited by SyncViews

Share on other sites
The technical word for "the contents of sqrt" is the discriminant.

Share on other sites

Besides this you missed one solution here as a quadratic can have only one real root as well when the discriminant is zero.

Edited by NightCreature83

Share on other sites

Well it doesn't really miss the solution, it just prints the same one out twice, and SyncView's code carries on if d == 0.

SyncView later storing sqrt(d) in an int isn't a great plan though ;)

Share on other sites

Fixed :) . Fortunately most compilers will warn about a double to int implicit conversion.

While d == 0 in some cases is useful, I think in practice most of the time your going to end up with just being near zero due to rounding errors at various stages, including the inputs them selves. If the single root situation is of interest for whatever you are doing, you will need to decide how close is close enough.

• 23
• 10
• 19
• 16
• 14