Doing arithmetic in functions

Hi. I'm trying to make a program to do some simple arithmetic for random numbers but for some reason, my getResult function isn't working. It's compiling fine but it seems to just put some random number as my results instead of what I specified in my function. Thanks in advance.

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
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void generate2Digits (int&, int&);
void generateOperation (char&);
void printExpression (int, int, char);
int getResult (int, int, char);

int main ()
{
int a, b, result;
char operand;
srand (time (NULL));

printExpression (a, b, operand);
getResult (a, b, operand);
cout << result;
}

void generate2Digits (int& a, int& b)
{
	a = rand () % (9 - 1) + 1;
	b = rand () % (9 - 1) + 1;
}

void generateOperation (char& operand)
{
	operand = rand () % 3;
		
		switch (operand)
		{
			case 0: cout << "+";
					break;
			case 1: cout << "-";
					break;
			case 2: cout << "*";
					break;
		}
	
}

void printExpression (int a, int b, char operand)
{
	generate2Digits (a, b);
		{
		cout << a << " "; 
		generateOperation (operand);
		cout <<  " " << b << "=" << " ?" << endl;
	
		}
	
}

int getResult (int a, int b, char operand)
{
	int result;
	
	if (operand = 0)
		result = a + b;
	else if (operand = 1)
		result = a - b;
	else result = a * b;
	
	return result;
	
}

Last edited on
You are using the assignment operator in your logic conditions.

use ==
Sorry but which logic conditions are you referring to.
Line 18, getResult() returns a value, it should be assigned to the variable result.

Function printExpression(), despite its name, doesn't just print. It actually generates the values. Therefore its parameters should each be passed by reference.

As already mentioned, you should use the == operator to test for equality rather than the = assignment operator. That's in the if statements within function getResult().
I see. Thank you very much for the help.
Topic archived. No new replies allowed.