I'm trying to create a game that generates a random number then you have to use a calculator to come with an arithmetic to match that number to win. I made the calculator using a simple switch statement but now I need to store that value from the calculator to compare to the random number, is there a way to do this? Here is a snippet of the code so far, feel free to manipulate it... I tried to store it with float calcnum but it didn't work.
switch (calc)
{
case '+':
cout << "The Answer is: " << num1 + num2 << endl;
float calcnum = calc;
break;
case '-':
cout << "The Answer is: " << num1 - num2 << endl;
float calcnum = calc;
break;
case '*':
cout << "The Answer is: " << num1 * num2 << endl;
float calcnum = calc;
break;
case '/':
cout << "The Answer is: " << num1 / num2 << endl;
float calcnum = calc;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! Enter the correct operator and two numbers";
break;
}
Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.
You can use the preview button at the bottom to see how it looks.
switch (calc)
{
case'+':
{
cout << "The Answer is: " << num1 + num2 << endl;
float calcnum = calc;
break;
}
case'-':
cout << "The Answer is: " << num1 - num2 << endl;
float calcnum = calc;
break;
case'*':
cout << "The Answer is: " << num1 * num2 << endl;
float calcnum = calc;
break;
case'/':
cout << "The Answer is: " << num1 / num2 << endl;
float calcnum = calc;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! Enter the correct operator and two numbers";
break;
}
It has been my experience that to define a variable in a switch the case statement need a set of {}s. Ad demonstrated in case '+':. The problem with this is that the variable becomes local to the {}s. And when you leave the closing } the variable is destroyed.
It is better to define "calcnum" outside of the switch. Also prefer to use "double"s over "float"s.
And try to use the new line, (\n), over the function "endl". With the new standards and newer compilers the (\n) works much the same as "endl", but with less time involved.