How to code basic calculation without if statements?

Hey guys, I'm just starting out and trying to build a rudimentary calculation program. Users input two numbers and an operand in one function, and the next function uses if statements to determine what to do next, as shown below:

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
#include "stdafx.h"
#include <iostream>
using namespace std;

int x;
int y;
char z;

int readNumber()
{
	cout << "Input integer 1\n";
	cin >> x;
	cout << "Input integer 2\n";
	cin >> y;
	cout << "Input operand\n";
	cin >> z;
	return 0;
}

int writeAnswer(int x, int y, char z)
{
	int Answer;
	if (z == '+')
		Answer = x + y;
	if (z == '-')
		Answer = x - y;
	if (z == '*')
		Answer = x * y;
	if (z == '/')
		Answer = x / y;
	cout << x << " " << z << " " << y << " = " << Answer << endl;
	return 0;
}

int main()
{
	readNumber();
	writeAnswer(x, y, z);
	return 0;
}


Is there any way to structure it differently so that C++ recognizes the operand and applies it to the two integers on its own, or is the process above really the simplest way to go about it?
Last edited on
You can use switch statement ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
switch(z)
{
case'+' :
Answer = x + y;
break;
case'-':
Answer = x - y ; 
break ; 
case'*':
Answer = x * y ;
break;
case'/':
Answer = x / y;
}


or nested if else
1
2
3
4
5
6
7
8
9
if (z == '+')
	Answer = x + y;
else if (z == '-')
	Answer = x - y;
else if (z == '*')
	Answer = x * y;
else if (z == '/')
	Answer = x / y;
Or do this functional style:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <map>
#include <functional>

double calculate(double first, double second, char op)
{
    static const std::map<char, std::function<double(double, double)>>  action = {
        {'+', std::plus<double>()},       {'-', std::minus<double>()},
        {'*', std::multiplies<double>()}, {'/', std::divides<double>()},
    };
    if(action.find(op) != action.end())
        return action.at(op)(first, second);
    else
        return 0.0/0.0;
}

int main()
{
    double first, second;
    char op;
    while(std::cin >> first >> op >> second)
        std::cout << calculate(first, second, op) << '\n';
}
Huh, didn't even know about some of these statement types. Thanks! :)
Topic archived. No new replies allowed.