PDA

View Full Version : correct text for displaying remainder

hmcka
03-06-2012, 01:38 AM
Good evening. I'm very new to this, but very excited that I've gotten this code so close. I am trying to get the computer to determine if a number is even or not. This is what I have:

[CODE]
<script type = "text/javascript">
<!--
var firstNumber; // first string entered by user
var answer; // the division problem

// read in first number from user as a string
firstNumber = window.prompt("Enter an integer");

//how to get a remainder
var answer = firstNumber / 2

{
document.writeln(answer + ". This number is even.");
}

</script>

The bottom part is the problem. I am able to code that if the answer is greater than one, then return the following text, however, I can't for the life of me figure how to say... if the remainder is zero.

Thank you,

webdev1958
03-06-2012, 01:47 AM
You'll probably find it easier if you use the modulus operator (%) which returns the actual remainder of a division. If the remainder after dividing by 2 is 0 then the numerator is even, otherwise the numerator is an odd number.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
<style type="text/css"></style>
<script type="text/javascript">
function checkNumber(){
var num = Number(document.getElementById('txtInp').value);
if(num%2 == 0){ //num is even
}else{ //num is odd
}
document.getElementById('txtInp').value = '';
}
</script>
<body>
<div>
<input type="text" id="txtInp" />
<button onclick="checkNumber();">Check number</button>
</div>
</body>
</html>

hmcka
03-06-2012, 02:17 AM
ty. after pounding my head a bit more, i also changed the if then statement to

{
document.writeln(answer + ". This number is even.");
}

and that works in the way i want, but it also identifies odd numbers as odd which i don't have in my code. why?

webdev1958
03-06-2012, 02:20 AM
that works in the way i want, but it also identifies odd numbers as odd which i don't have in my code. why?

I'm not sure without seeing all of your updated code.

The demo I posted displays either odd or even in the alert() for each number entered in the textbox.

Also, wrap your code in code tags by first highligting your code and then clicking the # icon in the editors toolbar. It'll make your code easier to read.

hmcka
03-06-2012, 02:25 AM

webdev1958
03-06-2012, 02:31 AM

btw,

= means assign a value to something like var myNum = 123

== is a comparison operator to check if 2 variables are equal to each other.

felgall
03-06-2012, 04:54 AM
If you put the number first and the variable second in comparisons and use identically equal comparisons then leaving out an = will be much easier to spot.