View Full Version : modulus as condition?

07-26-2002, 06:14 PM
Is it possible to use the modulus operator in a condition?

With forum help, I've done the code for an addition (and subtraction and mult. ) game for my 8 year old. For division, I want the answer to be whole numbers. Tried using modulus operator as a condition but it doesn't seem to work in my several syntax efforts. Any suggestions? Ex:

function newProblem(){
numA = Math.floor(Math.random() * 100) + 1;
numB = Math.floor(Math.random() * 100) + 1;
if (numA%numB=0){
document.myForm.txtQuestion.value = + numA + " / " + numB;
var correctAnswer = numA/numB;
document.myForm.correctAnswer.value = correctAnswer;
document.myForm.txtAnswer.value = '';
} else {

Curious also: Is there a way to write a compound condition? So far I don't see this in any book or tutorial I have looked at. Previous attempts to solve the division problem involved trying to make a compound condition as in varieties of: if (numA>=numB) and if (numA%numB=0).



07-26-2002, 07:19 PM
You need to use the equality operater (==) and not the assignment operator (=) :):

if (somenum % divisor == 0) {

As for what you call compound conditions, you have the boolean and operator (&&):

if (somecondition && anothercondition) {
// do something if both are true

07-26-2002, 07:23 PM
duh! Certainly a newcomer's mistake! Thanks for setting me straight on that and on the && operator.


07-26-2002, 08:31 PM
How 'bout cuttin' through all the code clutter and use the Math.round() function?

And if you don't like your answer's rounded up sometimes, try Math.Floor() - which IS what you want.

Make it simple as possible - but no simpler.
- A. Einstein

07-26-2002, 08:35 PM
I could be wrong, but if I use Math.round() then it would still be possible to divide, say, 33 by 2 and get 16, and all would be whole numbers. Maybe there is more to your suggestion, since I haven't thought this through completely.

07-26-2002, 08:44 PM
Between my initial post and my modification of that post, you made your reply.

Use Math.floor(). That'll do it for ya.

07-26-2002, 08:48 PM
RadarBob -- thanks much, I'll do that. Beep