...

View Full Version : modulus as condition?



Beep
07-26-2002, 05: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 {
newProblem();
}
}

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).

Thanks.

Beep

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

if (somenum % divisor == 0) {
//bla
}

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

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

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

Beep

RadarBob
07-26-2002, 07: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

Beep
07-26-2002, 07: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.

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

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

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum