Clean up code

Basically what the title says. What can I do to simplify this (cut it down to only the necessary parts)? I'm trying to learn how to be more efficient. Please nothing too crazy. I'm a novice so anything beyond this level would be excessive for me.

#include <iostream>
using namespace std;
void getRandNum(int& n)
{
n = rand() % 10 + 1;
}
bool isAnswerRight(int n1, int n2, char ch)
{
int s;
switch (ch)//pass the character to switch
{
case '+'://based on operator we get
cout << n1 << "+" << n2 << "=";//output the question
cin >> s;//take input
if ((n1 + n2) == s)//if it is equal return true
return true;
else
return false;
break;
case '-':
cout << n1 << "-" << n2 << "=";//in the same way for subtraction and multiplication
cin >> s;
if ((n1 - n2) == s)
return true;
else
return false;
break;
case '*':
cout << n1 << "*" << n2 << "=";
cin >> s;
if ((n1 * n2) == s)//check result
return true;
else
return false;
break;
default:cout << "The operator is not dened";
return false;
}
}
void add(int n1, int n2)
{
int s;
while (!isAnswerRight(n1, n2, '+'))//call until we get right answer
{
cout << "The answer is wrong try again" << endl;
}
cout << "you got correct" << endl;//nally print correct
}
void subtract(int n1, int n2)
{
int s;
while (!isAnswerRight(n1, n2, '-'))//subtract function with '-' char
{
cout << "The answer is wrong try again" << endl;
}
cout << "you got correct" << endl;
}
void multiply(int n1, int n2)
{
int s;
while (!isAnswerRight(n1, n2, '*'))//multiply char is passed and until it is true
{
cout << "The answer is wrong try again" << endl;
}
cout << "you got correct" << endl;
}
int main()
{
int n1, n2;
char ch;
srand(1);
getRandNum(n1);
getRandNum(n2);
add(n1, n2);
getRandNum(n1);
getRandNum(n2);
subtract(n1, n2);
getRandNum(n1);
getRandNum(n2);
multiply(n1, n2);
return 0;
}
Your first challenge in being efficient is to properly indent your code and use code tags. <> icon on the right.
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>
#include <ctime>
#include <cstdlib>
using namespace std;

int getRandNum() { return 1 + rand() % 10; }

bool isAnswerRight( int n1, int n2, char ch )
{
   int s;
   cout << n1 << ch << n2 << "=";
   cin >> s;
   
   switch( ch )
   {
      case '+': return n1 + n2 == s;
      case '-': return n1 - n2 == s;
      case '*': return n1 * n2 == s;
      default:
         cout << "Operator not recognised\n";
         return false;
   }
}

void operation( int n1, int n2, char c )
{
   while( !isAnswerRight( n1, n2, c ) ) cout << "The answer is wrong. Please try again.\n\n";
   cout << "The answer is correct.\n\n";
}

int main()
{
   srand( time( 0 ) );
   for ( char c : { '+', '-', '*' } ) operation( getRandNum(), getRandNum(), c );
}
Last edited on
Topic archived. No new replies allowed.