Generating Random Math Operators in C++ - c++

So I am creating a program where I have to create random problem sets that have random numbers and operators. I had no problem making random numbers. However, I am confused on how to randomize the three operators I need to use (addition, subtraction, and multiplication). I know I have to use numbers to represent these three operators, but I don't understand how to do that. I have to use the random number generator in order to do this and If & Then statements. Here is my source code.
I've tried creating a separate constant called "const int MAXOP_VALUE = 3" . I am stuck on what to do afterward. How do I represent the addition, subtraction and multiplication operators as numbers?
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
/*Constants*/
const int MIN_VALUE = 1;
const int MAX_VALUE = 100;
/*Variables*/
int number_1;
int number_2;
int math_op;
/*Get the System Time*/
unsigned seed = time(0);
/*Seed the Random Number Generator*/
srand(seed);
/*Generates Random Numbers for the Math Problems*/
number_1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
number_2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
/*Answer to Problem*/
/*Explains How the Program Works*/
cout << "****************************************" << endl << endl;
cout << "Welcome to the awesome math tutor! \n";
cout << "Get ready to add, subtract, and multiply!" << endl << endl;
cout << "****************************************" << endl << endl;
cout << "How much is" << number_1 << math_op << number_2 << "?" <<
endl;
return 0;
}
I expect the output to be along the lines of this:
"What is 25 +42 ?"
"What is 54*3 ?"
"What is 76-2 ?"

One liner for generating random math_op. Remove the int math_op and put this line somewhere after srand(seed).
char math_op = "+-*"[rand() % 3];
And you may use switch-case statement for the actual calcuation.

Once you have the two random numbers, you can use another random number to generate the operation and expected result, something like:
char op; int expected;
switch(rand() % 3) {
case 0: op = '+'; expected = num1 + num2; break;
case 1: op = '-'; expected = num1 - num2; break;
default: op = '*'; expected = num1 * num2; break;
}
Then you'll be able to output the expression and compare what's entered with the expected result:
int answer;
std::cout << "What is " << num1 << " " << op << " " << num2 << "? ";
std::cin >> answer;
std::cout << "Your answer is " << (answer == expected) ? "right" : "wrong" << ".\n";
Normally I'd also suggest you check the expected result is okay, as in no overflow or divide-by-zero, or be wary of doing integer division where 5 / 2 == 2.
But with both numbers between one and a hundred, and divide-by-zero/integral-division being a non-issue as your specifications only allow for addition, subtraction, and multiplication, it should be fine.

Related

How to code in C++ mutiple return values to main from mutiple modules and display each modules totals?

I must write a program where the user can choose to practice with topic addition or topic multiplication that starts with a self-driven menu.
It must keep track of questions answered right, wrong and the number of questioned asked.
Which my current program is doing within each module(topic). Example Addition keeps track of the questions while the user is practicing Addition only and Multiplication does the same.
However, they are not being feedback to main, so they are not being added or displayed before the user can select another topic to practice or to exit the program.
Currently it is only to keeping track of the question (right /wrong/ total of questions) for each module (topic).
My goal is for the values to be passed to main and display the total number (right /wrong/ total of questions) before the user exits the program, but at the same time I must display the number of question in the Additional Topic and the Multiplication topic and provide a total.
Example Table of Addition, Multiplication and Totals ?
This is the code I have to start with. Can someone help me in how to code to return values of the (right /wrong/ total of questions) of the two topics and accomplish to display something like the table information.
******************************************************************************* /
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////
// Implementing menu driven programs.
// Function Prototypes.
int menu();
void sums();
void products();
int main()
{
srand(time(0));
int option;
do {
option = menu();
switch (option) {
case 1: {
sums();
break;
}
case 2: {
products();
break;
}
default:
cout << "Program exit" << endl;
}
} while (option != 6);
return 0;
}
int menu()
{
cout << "Please select an option" << endl;
cout << "1) Practice with Addition " << endl;
cout << "2) Pratice with Multiplication " << endl;
cout << "3) Exit the program " << endl;
int option;
cin >> option;
return option;
}
void sums()
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValue = 10;
const int maxValue = 99;
int y = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValue - minValue + 1)) + minValue;
// cout<< " the random number is x "<< x << endl;
cout << "What is " << x << " + " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x + y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
void products()
{
{
string keepgoing;
unsigned int quantity_total_questions = 0U;
unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;
do {
const int minValueOne = 0;
const int maxValueOne = 9;
const int minValueTwo = 10;
const int maxValueTwo = 99;
int y = (rand() % (maxValueOne - minValueOne + 1)) + minValueOne;
// cout<< " the random number is y "<< y << endl;
int x = (rand() % (maxValueTwo - minValueTwo + 1)) + minValueTwo;
// cout<< " the random number is x "<< x << endl;
cout << " What is " << x << " x " << y << " =" << endl;
int answer;
cin >> answer;
if (answer == (x * y)) {
cout << "Great!! You are really smart!!" << endl;
++quantity_correct_answers;
++quantity_total_questions;
}
else {
cout << "Oh Sorry Try Again." << endl;
++quantity_wrong_answers;
++quantity_total_questions;
}
cout << "Right: " << quantity_correct_answers;
cout << " Wrong: " << quantity_wrong_answers;
cout << " Total Questions: " << quantity_total_questions << endl;
cout << "Do you want to play again? [enter y for yes or n for no]" << endl;
cin >> keepgoing;
} while (keepgoing == "y");
}
}
I would create a structure that contains the number of total answers and number of correct answers—the incorrect ones can be inferred—and then pass a reference to an instance of the structure to the respective sums() and products() functions.
Those functions can then populate the structure elements and when they return, your main function can read them out, knowing exactly how many questions were asked, how many were answered, or whatever other information you want to record and retrieve.

How do I correctly implement a loop that asks the user if he wants to re-execute the code?

In one of my c++ class assignments, I was given the task:
Write a program that reads in a list of floating-point numbers and then prints out the count of the values, the average, and the standard deviation.
You can assume that the the user's input is always valid and that the list contains at least two numbers.
 You can assume that the numbers in the list are separated by one space character and that the character following the last number in the list is the newline character.
 Implement a loop in which the above actions are repeated until the user requests to quit.
I am struggling with the last step, where I need to ask the user if they want to continue. My code is as follow.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char counter;
do {
char ch = ' ';
int i = 0;
double sum = 0;
double average = 0;
double sum_squared = 0;
cout << "Please enter a list of values (of type double): ";
do {
double x;
cin >> x;
ch = cin.get();
i += 1;
sum += x;
double x_squared = pow(x, 2);
sum_squared += x_squared;
} while (ch != '\n');
average = sum / i;
double standard_deviation = sqrt((sum_squared - (pow(sum, 2) / i)) / (i - 1));
cout << "Number = " << i << endl;
cout << "Average = " << average << endl;
cout << "Standard deviation = " << standard_deviation << endl;
cout << "Continue? (y,n) "; cin >> counter;
} while (counter = 'y');
return 0;
}
I was expecting that when user enter y in the end, the program would re-execute. But it turned out to be weird. When I enter n, the code still re-execute. Can anyone explain why? Additionally, how do I correctly implement this function to my code? Thank you all for your help and response.
changing
counter = 'y'
to
counter == 'y'
near the end will yield the satisfactory result.

For loop - Magic number program

What changes should I make so that the user of this code can guess at the amount of magic numbers they choose, with three different chances to guess at each magic number? I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int magic; // This is a random number between 1 and 20
int guess; // This is the guess number being attempted (up to 3 guesses)
int magicguesses; // This is the amount of magic numbers being guessed attempted
int i;
int number; // This is the number the user guessed
bool numberismagic = false; // This is the flag variable
unsigned int seed;
seed = time(NULL);
srand(seed);
magic = rand() % 20 + 1;
cout << "How many magic numbers would you like to guess at today?\n";
cin >> magicguesses;
for (i = 1; i < magicguesses + 1; i++)
{
cout << "This is trial number:" << i << endl;
for (guess = 1; (guess < 4) && (!numberismagic); guess++)
{
cout << "This is guess number:" << guess << endl;
cout << "Guess a number between 1 and 20:" << endl;
cin >> number;
while ((number < 1) || (number > 20))
{
cout << "Your guess is invalid; guess a number between 1 and 20 \n";
cin >> number;
cout << endl;
}
if (number == magic)
{
cout << "You have guessed the magic number correctly! \n";
numberismagic = true;
}
else
{
cout << "Sorry - you guessed incorrectly! \n";
if (number > magic)
cout << "Your guess is too high \n" << endl;
else
cout << "Your guess is too low \n" << endl;
}
}
if (number != magic)
cout << "The magic number is:" << magic << endl;
}
return 0;
}
I'm not sure what your first question is, but for this question "I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly", you should edit the variable magic inside the first for loop so the magic number changes after the user guesses correctly or they run out of tries.
for (i=1;i<magicguesses+1;i++)
{
//magic equals new random number
//the rest of your code
}

Xcode C++ Errors preventing further output past srand()

I am working on a program that generates two random numbers and an if statement that generates either a "+" for addition or a "-" for subtraction. I currently cannot check and see what my putput is so I can correct any mistakes because the program runs my opening "Welcome" statement then displays in blue parentheses (lldb) and the code stops there. I noticed next to my srand(time(0)) function that it turned green and says "thread 1: breakpoint 1.1" and under it reads "Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'". Is there a way to workaround these or get the errors to go away? My code is below. Any help or insight would be appreciated, thanks!
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
cout << "Welcome to the Math Tutor!" << endl;
int N1, N2;
int O = rand() % 2;
int Result;
int Answer;
srand(time(0));
if(O == 2)
{
cout << "+";
}
else
{
cout << "-";
}
N1 = 100 + rand() % 999;
N2 = 100 + rand() % 999;
Result = N1 + O + N2;
cout << setw(10) << N1 << endl;
cout << setw(10) << N2 << O << "\n";
cout << setw(10) << "------\n\n";
cout << "Enter your answer: ";
cin >> Answer;
if(Answer == Result)
{
cout << "You are correct!\n\n";
}
else
{
cout << "You are incorrect, the correct answer is: " << Result << "\n\n";
}
cin.ignore(1);
return 0;
}
time(0) returns a value of type time_t, which apparently is a long on your machine.
When you pass this long to srand(), expecting an unsigned int, not all values of a long will fit in an unsigned int. You can shoehorn it in by using a cast to tell the compiler that you don't care much about this.
srand(static_cast<unsigned int>(time(0)));
As you look for some, more or less, random numbers, the loss of precision is not important in this case.

C++ simple game using a Loop program

This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.