multiplication & division not working

Feb 27, 2017 at 1:52pm
closed account (G2UR4iN6)
So I wrote this code and I found that the multiplication and division are not working. The only thing that works are the addition and subtraction.
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
#include <iostream>
using namespace std;

int a, b, c;

int main()
{
	cout << "Enter two numbers : ";
	cin >> a >> b;
	if (a + b)
	{
		c = a + b;
		cout << " The Answer is " << c;
		cout << "\n";
	}
	else if (a - b)
	{
		c = a - b;
		cout << " The Answer is " << c;
		cout << "\n";
	}
	else if (a*b)
	{
		c = a*b;
		cout << " The Answer is " << c << endl;
		cout << "\n";
	}
	else if (a/b)
	{
		c = a / b;
		cout << " The Answer is " << c << endl;
		cout << "\n";
	}
}
Feb 27, 2017 at 2:13pm
closed account (48T7M4Gy)
You need something like this to get it to work.

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
#include <iostream>
using namespace std;

int a = 0, b = 0, c = 0;
char op;

int main()
{
    cout << "Enter number operator number separated by spaces : ";
    cin >> a >> op >> b ;
    if (op == '+')
    {
        c = a + b;
        cout << " The Answer is " << c;
        cout << "\n";
    }
    else if (op == '-')
    {
        c = a - b;
        cout << " The Answer is " << c;
        cout << "\n";
    }
    else if (op == '*')
    {
        c = a*b;
        cout << " The Answer is " << c << endl;
        cout << "\n";
    }
    else if (op == '/' and b != 0)
    {
        c = a / b; // note integer divison
        cout << " The Answer is " << c << endl;
        cout << "\n";
    }
}
Last edited on Feb 27, 2017 at 2:14pm
Feb 27, 2017 at 2:15pm
What do you mean with 'not working'?

What are you trying to achieve with the if statements?

Feb 27, 2017 at 2:19pm
What is the purpose of your if statements at lines 10, 16, 22 and 28?
Lines 11-15 will execute only if the sum of a and b is non-zero.
If the sum of a and b is non-zero, non of the remaining statements will execute because of the else on line 16.

Likewise, lines 17-21 will execute only if a and b are not the same.
Lines 23-27 will execute only if the product of a and b is non-zero.
Get rid of the if statements.

BTW, you're doing integer division on line 30. You won't get the result you're expecting.
Feb 27, 2017 at 2:28pm
closed account (48T7M4Gy)
@OP

You can replace the cascade of if statements with a switch control but it's not the end of the world to leave it as it is because they both do they same thing.

An additional else to capture op's outside +, -, * and / would be a good move. A message where dividing by zero wouldn't go astray either.

Using a double in calculating division overcomes the pitfalls of integer division. eg cout << 1.0 * a /b << endl;
Topic archived. No new replies allowed.