africantraplord africantraplord - 3 years ago 136
C++ Question

Checking for divide by zero

In my program, given a random number of random operations using a random numbers ex. 2 + 5 / 2 - 5 + 2 * (9 - 5) / 2
-- I need to check if there will be a divide by zero error when calculating the numbers. How would I do this, and without getting an error myself?

code:

for (int i = 0; i < randNumOfOperations; i++) {
int randDecision = rand() % 5 + 1;
int randDecision2 = rand() % 4 + 1; // inside () operations
int randDecision3 = rand() % 4 + 1; // outside () operations
int randNum = rand() % 15 + 1;
int parenRandNum = rand() % 20 + 1;
int parenRandNum2 = rand() % 20 + 1;
std::string tempstr = std::to_string(randNum);
std::string tempstr2 = std::to_string(parenRandNum);
std::string tempstr3 = std::to_string(parenRandNum2);
switch (randDecision) {
case 1:
nStr.append(tempstr);
nStr.append(" + ");
break;
case 2:
nStr.append(tempstr);
nStr.append(" - ");
break;
case 3:
nStr.append(tempstr);
nStr.append(" * ");
break;
case 4:
nStr.append(tempstr);
nStr.append(" / ");
break;
default:
break;
}

if (randDecision == 5) { //( ) operations
nStr.append(" (");
switch (randDecision2) {
case 1:
nStr.append(tempstr2);
nStr.append(" + ");
nStr.append(tempstr3);
break;
case 2:
nStr.append(tempstr2);
nStr.append(" - ");
nStr.append(tempstr3);
break;
case 3:
nStr.append(tempstr2);
nStr.append(" * ");
nStr.append(tempstr3);
break;
case 4:
nStr.append(tempstr2);
nStr.append(" / ");
nStr.append(tempstr3);
break;
default:
break;
}

nStr.append(") ");

switch (randDecision3) {
case 1:
nStr.append(" + ");
break;
case 2:
nStr.append(" - ");
break;
case 3:
nStr.append(" * ");
break;
case 4:
nStr.append(" / ");
break;
default:
break;
}

}
}


The code puts the random expression into the string nStr.

Answer Source

I would look into how to build an expression tree and evaluate the expression using that. It would make it simple to check for divide by zero and it would be efficient. You could also use this for many different applications in the future. http://www.geeksforgeeks.org/expression-tree/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download