Reputation: 45
So I am trying to make a program which will generate random basic mathematical questions like addition, subtraction, etc.
While I am trying to generate division questions I made a do-while loop which runs until the prerequisite is met for division quesions.
But for some reason when I ask it to generate 20 division questions with none with remainder it always crashes.
Please help
Here's the code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int correct,total,MAXVAL;
const char oper[4]={'/','/','/','/'};
typedef struct data{
int first,second;
char operation;
}data;
data datagenerator(){
data newData;
newData.first= (rand()%MAXVAL);
newData.operation=oper[rand()%4];
newData.second=(rand()%MAXVAL);
return newData;
}
bool corrector(data newData){
bool isture=false;
switch(newData.operation){
case '/':
if((newData.first%newData.second)==0){
isture=true;
}
break;
case '*':
isture=true;
break;
case '+':
isture=true;
break;
case '-':
isture=true;
break;
}
return isture;
}
void quizer(){
system("CLS");
for(int counter=1;counter<=total;counter++){
cout<<"Q"<<counter<<": ";
data newData;
do{
newData=datagenerator();
}while(!corrector(newData));
cout<<newData.first<<newData.operation<<newData.second<<"\n";
}
cout<<"\nYou got "<<correct<<"/"<<total<<"correct\n";
}
int main(){
//srand((unsigned)time(0));
char x;
cout<<"How many questions do you want?"<<endl;
cin>>total;
cout<<"Enter the maximum value\n";
cin>>MAXVAL;
cout<<"Are you ready?\n";
cin>>x;
quizer();
system("PAUSE");
return 0;
}
Upvotes: 0
Views: 725
Reputation: 9843
Your generating a 0 as a second number and then trying to use it to divide by a number.
you can put a check like this
if(newData.second == 0) {
return false;
}
Upvotes: 1
Reputation: 1419
Your problem lies right on line 17 and 19. You are dividing by 0, assuming you are setting the value on MAXVAL to 0 when it asks you. With modulo division you need to be careful with that.
Upvotes: 0
Reputation: 1538
You need to check for a division by 0.
bool corrector(data newData){
bool isture=false;
switch(newData.operation){
case '/':
if(newData.second == 0) {
break;
}
if((newData.first%newData.second)==0){
isture=true;
}
...
Upvotes: 3