Dec 26, 2020 at 11:17am UTC
Hey! So I wrote this code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int a,b,c;
double x1,x2,delta;
cin>>a;
cin>>b;
cin>>c;
delta=b*b-4*a*c;
x1=(-b+sqrt(delta))/(2*a);
x2=(-b-sqrt(delta))/(2*a);
cout<<"x1="<<x1<<"x2="<<x2;
}
For some reason it only outputs "nan". Any ideas why? I tried with many inputs.
Dec 26, 2020 at 11:33am UTC
Yo! So I tried
Seems to work.
However, a, b, c should be
double , not int. And make sure that you only input equations with real roots; i.e. those for which b
2 -4ac>=0. Trying "2 1 2" rather than "1 2 1" would be a disaster, for example.
Last edited on Dec 26, 2020 at 11:46am UTC
Dec 27, 2020 at 11:32am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a {}, b {}, c {};
cout << "Enter a b c values: " ;
cin >> a >> b >> c;
if (const double discrim {b * b - 4.0 * a * c}; discrim >= 0) {
const double x1 {(-b + sqrt(discrim)) / (2.0 * a)};
const double x2 {(-b - sqrt(discrim)) / (2.0 * a)};
cout << "x1= " << x1 << " x2= " << x2;
} else
cout << "Complex roots!\n" ;
}
Last edited on Dec 27, 2020 at 11:33am UTC