This program ask user which arithmetic operation they want to play with then generates a random equation and lets the user answer it. When the user stop playing the game the program calculates the number of correct and answers and wrong answers.

I need some help because the program crashes when doing divisions.

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cmath> 
#include <cstdlib>
#include <iomanip>

//include header file
#include "lab_17_head.h"

using namespace std; 

int main( )
{

	//variable declaration
	int number1, number2;					//vars to store int values
	double intResult, doubleResult, result;			//vars to store the result
	char action;							//var for store the operator
	char flag;								//var to stor the choice
	int plusWins, plusLosses, plusTotal,	//plus stats for winning, losing, and total games played
		minuWins, minuLosses, minuTotal,	//minus stats for winning, losing, and total games played
		multWins, multLosses, multTotal,	//multiplication stats for winning, losing, and total games played
		diviWins, diviLosses, diviTotal;	//division stats for winning, losing, and total games played
	double answer;							//var for answer from the user

	//initializations
	plusWins = plusLosses = plusTotal = 0;	
	minuWins = minuLosses = minuTotal = 0;
	multWins = multLosses = multTotal =	0;
	diviWins = diviLosses = diviTotal = 0;	

	//show welcome message
	welcome(); 

	//enter your choice
	getChoice(flag); 

	//start loop to play the game
	while(flag=='y' || flag=='Y')
	{
		//get operator
		getOperator(action); 
		
		//four cases for action
		switch(action)
		{
			case '+':						//do addition	
					//get two random numbers of two digits
					getTwoNumbers(number1, number2); 
					//add
					intResult = add(number1, number2); 
					//getAnsers from the user
					getAnswer(number1, number2, action, answer); 
					//win or loss
					addGame(intResult, static_cast<int>(answer), plusWins, plusLosses, plusTotal); 
					break; 
		
			case '-':						//do substraction	
					//get two random numbers of two digits
					getTwoNumbers(number1, number2); 
					//add
					intResult = minus(number1, number2); 
					//getAnsers from the user
					getAnswer(number1, number2, action, answer); 
					//win or loss
					minuGame(intResult, static_cast<int>(answer), minuWins, minuLosses, minuTotal); 
					break; 

			case '*':						//do multiplication	
					/***************************************************
					 This part is for you to complete
					 ***************************************************/
					//get two random numbers of two digits
					getTwoNumbers(number1, number2); 
					//multiply
					intResult = multiply(number1, number2); 
					//getAnsers from the user
					getAnswer(number1, number2, action, answer); 
					//win or loss
					multiGame(intResult, static_cast<int>(answer), multWins, multLosses, multTotal); 
					break; 
					
			
			case '/':						//do division	
					/***************************************************
					 This part is for you to complete
					 ***************************************************/
				//get two random numbers of two digits
					getTwoNumbers(number1, number2); 
					//add
					intResult = divide(number1, number2); 
					//getAnsers from the user
					getAnswer(number1, number2, action, answer); 
					//win or loss
					diviGame(result, static_cast<int>(answer), diviWins, diviLosses, diviTotal); 
					break; 

			
			default: 
					cout<<action<<" is not a valid operator ." <<endl; 
		}

		//get choice
		getChoice(flag); 
	}

	//show stats
	statsShow(plusWins, plusLosses, plusTotal, minuWins, minuLosses, minuTotal,
		      multWins, multLosses, multTotal, diviWins, diviLosses, diviTotal);	

	//byebye
	bye(); 

	//well done and exit
	return 0; 
}

This is the header used

#include <iostream>
#include <cstring>

using namespace std; 

#ifndef		LAB_17_HEAD_H		
#define		LAB_17_HEAD_H

//show welcome message
void welcome()
{
	cout<<" Welcome to my math world and enjoy some training ...... "<<endl; 
	return;						//no value is returned here 
}

//get the choice
void getChoice(char & ch)						//use reference paramter to receive the choice 
{
	 cout<<"\n Would you like to play the game? (y/n) => "; 
	 cin>>ch;					//get the choice
	 return; 
}

//get operator
void getOperator(char & action)					//use reference paramter to receive the action 
{
	cout<<"\n Which operation do you like to play? (+, -, *, /) => "; 
	cin>>action; 
	return;						//get the choice
}

//get two random numbers of two digits
void getTwoNumbers(int & number1, int & number2) //use reference paramter to receive the action 
{
	unsigned seed;				//local variable for random seed
	
	//get a random seed
	cout<<"\n Give me an integer for random =>"; 
	cin>>seed; 

	//set the random seed
	srand(seed);
	
	//get two random numbers of single digit
	number1 = rand()%10; 
	number2 = rand()%10; 

	return; 
}


//do addition					
int add(const int number1, const int number2)	//const value parameters
{
	return number1 + number2;	//return the sum
}

//do substraction					
int minus(const int number1, const int number2) //const value parameters
{
	return number1 - number2;	//return the substraction
}

//do addition					
int multiply(const int number1, const int number2)//const value parameters
{
	return number1 * number2;	//return the multiplication
}

//do addition					
double divide(const int number1, const int number2)//const value parameters
{
	return static_cast<double>(number1) / static_cast<double>(number2);	
								//return the division
}

//getAnsers from the user
void getAnswer(const int number1, const int number2, const char action, 
			   double & answer)
{
	cout<<endl<<number1<< "  " <<action <<"  " <<number2<< " = ?  "; 
	cin>>answer; 
}

//addition win or loss
void addGame(const int intResult, const int answer, 
			   int & plusWins, int & plusLosses, int & plusTotal)
{
	if (answer == intResult)	//decide winning
		plusWins++; 
	else						//or loss
		plusLosses++;

	plusTotal++;				//counting the games
}

//substrcation win or loss
void minuGame(const int intResult, const int answer, 
			   int & minuWins, int & minuLosses, int & minuTotal)
{
	/*********************************************************
	This part is for you to complete
	*********************************************************/
	if (answer == intResult)	//decide winning
		minuWins++; 
	else						//or loss
		minuLosses++;

	minuTotal++;
}

//multiplication win or loss
void multiGame(const int intResult, const int answer, 
			   int & multWins, int & multLosses, int & multTotal)
{
	/*********************************************************
	This part is for you to complete
	*********************************************************/
	if (answer == intResult)	//decide winning
		multWins++; 
	else						//or loss
		multLosses++;

	multTotal++;
}

//division win or loss
void diviGame(const double result, const double answer, 
			   int & diviWins, int & diviLosses, int & diviTotal)
{
	/********************************************************
	This part is for you to complete
	********************************************************/
	if (answer == result)	//decide winning
		diviWins++; 
	else						//or loss
		diviLosses++;

	diviTotal++;
					
}

//show stats
void statsShow(const int plusWins, const int plusLosses, const int plusTotal, 
			   const int minuWins, const int minuLosses, const int minuTotal,
		       const int multWins, const int multLosses, const int multTotal, 
			   const int diviWins, const int diviLosses, const int diviTotal)
{
	double plusScore, 			//local variable for scores
		   minuScore,
		   multScore,
		   diviScore;

	//compute the scores
	plusScore = plusTotal==0 ? 0: static_cast<double>(plusWins)/static_cast<double>(plusTotal);
	plusScore *= 100;
	minuScore = minuTotal==0? 0: static_cast<double>(minuWins)/static_cast<double>(minuTotal);
	minuScore *= 100;
	multScore = multTotal==0? 0: static_cast<double>(multWins)/static_cast<double>(multTotal);
	multScore *= 100;
	diviScore = diviTotal==0? 0: static_cast<double>(diviWins)/static_cast<double>(diviTotal);
	diviScore *= 100;
	
	cout<<endl; 

	//for addition
	cout<<" You played "<<plusTotal<<" additions."<<endl
		<<" You won " <<plusWins <<" many times." <<endl
		<<" You lost "<<plusLosses<<" many times." <<endl
		<<" Your addition score is " <<setprecision(2)<<fixed<<showpoint
		<< plusScore
		<<endl<<endl;
	
	//for substraction
	cout<<" You played "<<minuTotal<<" substractions."<<endl
		<<" You won " <<minuWins <<" many times." <<endl
		<<" You lost "<<minuLosses<<" many times." <<endl
		<<" Your substration score is " <<setprecision(2)<<fixed<<showpoint
		<< minuScore
		<<endl<<endl;

	//for multiplication
	cout<<" You played "<<multTotal<<" multiplications."<<endl
		<<" You won " <<multWins <<" many times." <<endl
		<<" You lost "<<multLosses<<" many times." <<endl
		<<" Your multiplication score is " <<setprecision(2)<<fixed<<showpoint
		<< multScore 
		<<endl<<endl;
	
	//for division
	cout<<" You played "<<diviTotal<<" divisions."<<endl
		<<" You won " <<diviWins <<" many times." <<endl
		<<" You lost "<<diviLosses<<" many times." <<endl
		<<" Your division score is " <<setprecision(2)<<fixed<<showpoint
		<< diviScore 
		<<endl<<endl;

}

//byebye
void bye()
{
	cout<<"Hope you enjoyed playing this game. Byebye." <<endl<<endl;
	return; 
}


#endif

Recommended Answers

All 19 Replies

You should check where the program crashes, and read the error message(s).

Check your arguments closely - what's being used here, and what is being used without having a value assigned?

intResult = divide(number1, number2); 
	//getAnsers from the user
	getAnswer(number1, number2, action, answer); 
	//win or loss
	diviGame(result, static_cast<int>(answer), diviWins, diviLosses, diviTotal);

I'm confused. You store a result to intResult, but that value returned is a double. What do you really mean?

Shouldn't that value you got back from the divide( ) function be what's sent to diviGame( ) for evaluation?

And in diviGame(), you are trying to compare two doubles for equality - that's a crapshoot at best.

Why do you put the const modifier on so many of the parameters that are passed by value? That's not a common thing to do.

I'm confused. You store a result to intResult, but that value returned is a double. What do you really mean?

I see that the intResult variable is a double type.

There are issues with the types alright.

OK. I've tried some changes and seems it's working now(hopefully)

change your diviGame() function to

diviGame(intResult, answer, diviWins, diviLosses, diviTotal);

Change you divide() function(in the header file) to :

double divide(const int number1, const int number2)//const value parameters
{
	
	return double((double)number1 / (double)number2);
								//return the division
}

and that should return an answer with correct precision.

Hope that helps.
Cheers

I see...I changed "intResult" to "doubleResult" and it doesn't crash anymore, but now the program takes any answer to a division which has decimals or are in fraction form as wrong answer, any idea on how to fix this? sorry I;m new to C++

Oh and the adding and subtracting parts were already in the program I just has to complete multiplying and diving so I just followed the format on adding and subtracting.

Edit: Sorry abhi_elementx I didn't see you posts I'm going to try that now, thanks.

Ok your way it does get decimals, but it still wont get fractions it takes them as wrong answers
ex. "5 / 6 = ?" and instead of typing "0.8333..." I answer "5/6" and it takes it as wrong.
Any ideas?

I tried this:
Welcome to my math world and enjoy some training ......

Would you like to play the game? (y/n) => y

Which operation do you like to play? (+, -, *, /) => /

Give me an integer for random =>3

1.2
6 / 5 = ? 1.2

Would you like to play the game? (y/n) => n

You played 0 additions.
You won 0 many times.
You lost 0 many times.
Your addition score is 0.00

You played 0 substractions.
You won 0 many times.
You lost 0 many times.
Your substration score is 0.00

You played 0 multiplications.
You won 0 many times.
You lost 0 many times.
Your multiplication score is 0.00

You played 1 divisions.
You won 1 many times.
You lost 0 many times.
Your division score is 100.00


Shudnt this be the output?

Yes that's right but you did 6/5, try the random integer of 3.
it is 5/6 which is 0.83333333333333333333333333333... so you need that in a fraction but it takes the fraction as wrong, I just need it to be able to take fractions.

Always Check for division with zero .. the rand might get it zero

Ah. Its a simple error on our hand.
We forgot that floats cannot be compared directly
0.33333 = 0.33 will not return true always and even it does, change in the execution environmet(compiler, hardware, etc) will behave unpredictably.
try :

void diviGame(const double result, const double answer, 
			   int & diviWins, int & diviLosses, int & diviTotal)
{
	if (fabs(answer - result) < 0.01 )	//decide winning
		diviWins++; 
	else						//or loss
		diviLosses++;

	diviTotal++;
					
}

and see if it works now....
Also read this: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

Hope that solves the problem.
Cheers

Yea with that it gets decimals but it wont get fractions and when I put a fractions the game terminates and shows the results it doesn't even ask if the user wants to keep playing.

Help please?

Ah. Floats cant be compared directly. And even if you get a result, the same code might not work on different runtime environments(cmpiler, hardware, etc). Therefore u need to set a margin.
Improved code:

void diviGame(const double result, const double answer, 
			   int & diviWins, int & diviLosses, int & diviTotal)
{

	if (fabs(answer - result) < 0.01 )	//decide winning
		diviWins++; 
	else						//or loss
		diviLosses++;

	diviTotal++;
}

Hope this helps.

Cheers

oh. please ignore the above post :P

See, if u want to compare fractions, why not covert the fraction into string and then compare the strings(the answer and the result)

Never mind got it.
Thanks a lot for your help! =)

Good Afternoon,

I'm getting the error: coversion from double to const int, possible loss of data on case '+' on addGame function on the cpp file
error: conversion from double to const int possible loss of data on case '-' on minuGame function in the cpp file
error: conversion from double to const int possible loss of data on case '*' on multiGame function in the cpp file
error: unreferenced local variable in the cpp file

Poloblue, I thought you knew by now that if you have a question, you must open your own theread, and not to hijack threads that are older than 3 months.
Please, open your thread in order to receive answers to your question.
And by your erros I do get that you are trying either to assign a double to an int, or you have missplaced some operations.
Open your own thread, put the part of the code that crashes your program, put there also the error, and we'll talk.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.