Quadratic equation (Help).

When i run this code it outputs wrong answers.

For example A=-2 , B=1 , C=1 then x1 = -0.5 x2 = 1.
Instead it outputs that x1=1 and x2=1,4013e-045 ???

I am super noob at C++ would be grateful if someone helped me out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<cmath>
#include<cstring>

using namespace std;

int main()
{
	float Input[3];
	char z[4] = {'A','B','C','D'};
	float x1,x2;
	
	for(int i=0;i<3;i++)
	{
		cout << "Insert " << z[i] << ":";
		cin >> Input[i];
		cout << endl;
		if(z[i]=='D') goto next;
	}
	next:
	float test = Input[1]*Input[1]-4*Input[0]*Input[2];
	if(test < 0) cout << "Roots are complex!" << endl;
	else
	{
		x1 = (-Input[1] + sqrt(test)) / (2*Input[0]);
		x1 = (-Input[1] - sqrt(test)) / (2*Input[0]);
		cout << x1 << endl;
		cout << x2 << endl;
	}
	
	
	return 0;
}
You could change floats to doubles to give yourself more precision. But the underlying problem that would still remain is that floating-point arithmetic is inherently inexact; your computer only has finite numeric precision.
http://floating-point-gui.de/basic/

Instead, change the way you print the output so that it makes really small numbers just round to 0.

1
2
3
4
5
6
7
8
9
#include <iomanip>
#include <iostream>

int main()
{
    double a = 4.013e-045;
    std::cout << a << std::endl; // display default
    std::cout << std::fixed << std::setprecision(10) << a << std::endl; // display "rounded" to 10th decimal
}

The problem is that you wrote x1 on both lines 25 and 26. Change the second one to x2.
And input variable names of a, b, and c would be a lot clearer and neater!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double a, b, c;
    cout << "A: ";   cin >> a;
    cout << "B: ";   cin >> b;
    cout << "C: ";   cin >> c;

    double det = b * b - 4 * a * c;
    if (det < 0)
        cout << "Roots are complex!\n";
    else {
        double sq = sqrt(det);
        double x1 = (-b + sq) / (2 * a);
        double x2 = (-b - sq) / (2 * a);
        cout << '{' << x1 << ", " << x2 << "}\n";
    }

    return 0;
}

Thanks @ganado and @tpb I am so blind lol!
Topic archived. No new replies allowed.