simple calculator

i'm sure it is just a simple mistake somewhere but no matter what 2 values i enter, the result always ends up as 6.95322e-310

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
double calculate(char op, double n1, double n2)
{
    double var;
    switch (op)
    {
    case '+':
        var = n1 + n2;
        break;

    case '-':
        var = n1 - n2;
        break;

    case '*':
        var = n1 * n2;
        break;

    case '/':
        var = n1 / n2;
        break;
    }
}

int main()
{
    char op; double n1, n2, var;
    cout << "Enter x to end program" << endl;
    cout << "Enter the desired operand for the problem:" << endl;
    cin >> op;
    while(op != 'x')
    {
        cout << "Enter the first number:" << endl;
        cin >> n1;
        cout << "Enter the second number:" << endl;
        cin >> n2;
        cout << endl;
        calculate(op, n1, n2);
        cout << "The result is " << var << endl;
        cout << endl;
        cout << "Enter the desired operand for the problem:" << endl;
        cin >> op;
    }
    return 0;
}
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
50
51
52
53
54
55
56
57
58
#include <iostream>

double calculate(char op, double n1, double n2)
{
    double var = 0.0 ; // initialise to zero

    switch (op)
    {
    case '+':
        var = n1 + n2;
        break;

    case '-':
        var = n1 - n2;
        break;

    case '*':
        var = n1 * n2;
        break;

    case '/':
        var = n1 / n2;
        break;
    }

    return var ; // return the result of the calculation
                 // note: we return zero if op is not one of +-*/
}

int main()
{
    char op;

    std::cout << "Enter x to end program\n"
              << "Enter the desired operand for the problem: " ;
    std::cin >> op;

    while(op != 'x')
    {
        double n1, n2 ;
        std::cout << "Enter the first number: " ;
        std::cin >> n1;
        std::cout << "Enter the second number: " ;
        std::cin >> n2;

        // store the value returned by the function in result
        const double result = calculate(op, n1, n2);

        // and print out the result
        std::cout << "The result is " << result << "\n\n" ;

        // accept the value for the next operation
        std::cout << "Enter the desired operand for the problem: " ;
        std::cin >> op;
    }

    // there is an implicit return 0; at the end of main
}
Topic archived. No new replies allowed.