Problem with an equation.

Hello. Most of the information is in the code.
And if you're wondering why I output it to the console window it's because I love watching my programs 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//Program to work out how to use the numbers entered by the user can be used to make the number 24.

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void populate(double numbers[], int limit);

int main()
{
	srand((unsigned) time(0));
	char operators[4] = {'+','-','*','/'};
	double numbers[4];
	cout << "Enter the 4 numbers:" << endl;
	populate(numbers, 4);
	double answer = 0;
	
	while(answer != 24)
	{
	/* answer = [how do I do this?]  Equation below goes here, but if I were to write: 
				numbers[0] operators[rand() % 4] numbers[1] etc
			    then it expects a ; because it's not an actual equation (no operators), but I can't
			    use actual operators because I'm randomly (well, kind of) generating them using an array. 
				My question is:
			    How exactly would I enter the below equation into answer? Does my code need a revamp? */

	cout << numbers[0] << " " << operators[rand() % 4] << " "; 
	cout << numbers[1] << " " << operators[rand() % 4] << " "; // i.e. outputs 3 - 7 + 4 * 2 = answer
	cout << numbers[2] << " " << operators[rand() % 4] << " "; 
	cout << numbers [3] << " = " << answer << endl;
	}
	cout << endl << "Done!";

	char f;
	cin >> f;
	return 0;
}

void populate(double numbers[], int limit)
{
	double input;
	for(int i = 0; i < limit; ++i)
	{
	cout << i + 1 << ")"; //takes user input to specify the four numbers
	cin >> input;
	numbers[i] = input;
	}
}
Oh man, that is a doozy.
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
double doOperation(double operand1, char anOperator, double operand2)
{
     double result = operand1;

     switch(anOperator)
     {
          case '+':
               result += operand2;
               break;
          case '-':
               result -= operand2;
               break;
          case '*':
               result *= operand2;
               break;
          case '/':
               result /= operand2;
               break;
     }

     return result;
}

int main()
{
     ...

     answer = numbers[0];
     cout << numbers[0];

     for(int i=1; i<= 3; i++)
     {
          char randomOperator = operators[rand() % 4];
          cout << " " << randomOperator << " " << numbers[i];

          answer = doOperation(answer, randomOperator, numbers[i]);
     }

     cout << " = " << answer << endl;

     ...
}
Last edited on
Ah! A switch statement. I feel silly for not thinking of that. Thank you, shacktar.
Topic archived. No new replies allowed.