I can't find the mistakes in the code, plz help.

There's something wrong with the code, it keep print wrong results.

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double a,b,c,disc=(b*b)-(4*a*c);
    double x1=((-b)+(sqrt(disc)))/(2*a);
    double x2=((-b)-(sqrt(disc)))/(2*a);

    cout << "enter a in your function\n";
    cin >> a;

    cout << "enter b in your function\n";
    cin >> b;

    cout << "enter c in your function\n";
    cin >> c;

    if (disc>=0){
        cout << "x1=" << x1 << "\n";
        cout << "x2=" << x2 << "\n";
    }else{
    cout << "there's no real roots.\n";
    }

    return 0;
}
In your code, you calculate x1, x2 and disc before you tell it what values to use for a, b and c. Do you see any problem with doing that? Any problem with making it do the calculations before you tell it the numbers to use? Any way that might not work?
Last edited on
That's because you calculate the roots/discriminant before the user inputs a, b and c.

The logic should be like this.
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
// declare and initialise variables
double a = 0.0, b = 0.0, c = 0.0, disc = 0.0;

// ask the user to input a, b and c
cout << "enter a in your function\n";
cin >> a;

cout << "enter b in your function\n";
cin >> b;

cout << "enter c in your function\n";
cin >> c;

// calculate discriminant and roots
disc = (b*b) - (4*a*c);
x1 = ( (-b) + (sqrt(disc)) ) / (2*a);
x2 = ( (-b) - (sqrt(disc)) ) / (2*a);

// display calculated results
if (disc >= 0){
    cout << "x1 = " << x1 << "\n";
    cout << "x2 = " << x2 << "\n";
}
else{
	cout << "there's no real roots.\n";
}
Last edited on
now I put the formulas right before the if statement and delete the formulas at the declarations, it's still print out wrong thing.
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>

using namespace std;

int main()
{
    double a,b,c,disc;
    double x1,x2;

    cout << "enter a in your function\n";
    cin >> a;

    cout << "enter b in your function\n";
    cin >> b;

    cout << "enter c in your function\n";
    cin >> c;

    x1=((-b)+(sqrt(disc)))/(2*a);
    x2=((-b)-(sqrt(disc)))/(2*a);
    disc=(b*b)-(4*a*c);

    if (disc>=0){
        cout << "x1=" << x1 << "\n";
        cout << "x2=" << x2 << "\n";
    }else{
    cout << "there's no real roots.\n";
    }

    return 0;
}
I haven't read through your code too carefully but.

1
2
x1=((-b)+(sqrt(disc)))/(2*a);
x2=((-b)-(sqrt(disc)))/(2*a);


You never use x1 and x2 after you've calculated them, why?


Also in your calculations, you say sqrt(disc). But what do you mean by that. What is "disc"? It has no value, you give value to the disc after you've used it. That aint right man.
Thanks.
Topic archived. No new replies allowed.