Quick question for switch statement

Hello out there!

I've modified my older version of 'The quadratic equation calculator' to a function.. But it seems like i can't use a switch statement like this? Do i really have to use if/else statements?


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
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <math.h>

using namespace std;

int quadratic(int a, int b, int c)
{
    int discriminant = (pow(b,2)-4*a*c);
    switch(discriminant)
    {
    case(discriminant>0):
    cout << "x is: " << (-b+sqrt(discriminant))/(2*a);
    cout << "x is: " << (-b-sqrt(discriminant))/(2*a);
    break;

    case(discriminant==0):
    cout << "x is: " << -b/(2*a);
    break;

    case(discriminant<0):
    cout << "No solutions";


    return discriminant;
    }

}



int main()
{
    int a,b,c;
    cout << "Quadratic equation calculator" << endl << endl;
    cout << "Enter a: ";
    cin >> a;
    cout << "Enter b: ";
    cin >> b;
    cout << "Enter c: ";
    cin >> c;

    quadratic(a,b,c);

    return 0;
}
Last edited on
closed account (LA48b7Xj)
A switch statement tests a value against a set of constants.

So yea, you will need if statements for that.
Last edited on
Oh i see. Thanks krako!
It will look like this then:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

#include <iostream>
#include <math.h>

using namespace std;

int quadratic(int a, int b, int c)
{
    int discriminant = (pow(b,2)-4*a*c);
    if(discriminant>0)
    {
    cout << "x_1 is: " << (-b+sqrt(discriminant))/(2*a) << endl;
    cout << "x_2 is: " << (-b-sqrt(discriminant))/(2*a);
    }

    if(discriminant==0)
    {
    cout << "x is: " << -b/(2*a);
    }

    if(discriminant<0)
    {
    cout << "No x-values for this equation";
    }

    return discriminant;
    }





int main()
{
    int a,b,c;
    cout << "Quadratic equation calculator" << endl << endl;
    cout << "Enter a: ";
    cin >> a;
    cout << "Enter b: ";
    cin >> b;
    cout << "Enter c: ";
    cin >> c;

    quadratic(a,b,c);

    return 0;
}

Topic archived. No new replies allowed.