Reputation: 71
For a beginners JS assignment I need to divide numbers between each other and always beginning with the biggest number. So I never get decimal numbers. But when the usage of a 0 is involved then the output should give an alert that using a 0 is not allowed.
So I added a second if statement
if (nGetal2 == 0 || nGetal1 == 0){
sResultaat += " 0 niet toegelaten in deze uitvoering";
console.log(sResultaat);
}
But this makes the output again giving decimal numbers. 9 / 3 should be 3 and 3 / 9 should also be 3 because the biggest number is chosen for every dividing.
I thougt if I used a || operand that I could say that either nGetal1 or nGetal2 should never do anything if a 0 is used.
<script>
var eKnop = document.querySelector('#deKnop');
eKnop.onclick = bereken;
function bereken() {
console.log('knop werkt')
var eGetal1 = document.getElementById('getal1');
var eGetal2 = document.getElementById('getal2');
// de getallen
var nGetal1 = parseInt(eGetal1.value);
var nGetal2 = parseInt(eGetal2.value);
var sResultaat = "";
if(nGetal1 > nGetal2) {
sResultaat = nGetal1 / nGetal2;
}
if (nGetal2 == 0 || nGetal1 == 0){
sResultaat += " 0 not allowed";
}
else {
sResultaat = nGetal2 / nGetal1;
}
console.log(sResultaat);
}
</script>
https://stackoverflow.com/help/minimal-reproducible-example
Upvotes: 0
Views: 127
Reputation: 45736
Your if
/else
is set up wrong.
You do this first bit of division if nGetal1 > nGetal2
. Then, you check nGetal2 == 0 || nGetal1 == 0
, and if that's false, you go to the else
, and do division again; overwriting the first division result. I believe you meant:
if (nGetal2 == 0 || nGetal1 == 0){
sResultaat += " 0 not allowed";
} else if (nGetal1 > nGetal2) { // Only attempt division if neither operand is 0
sResultaat = nGetal1 / nGetal2;
} else {
sResultaat = nGetal2 / nGetal1;
}
console.log(sResultaat);
If either operand is 0, both of the division checks are skipped. If they aren't 0, nGetal1 > nGetal2
is checked. If that check is true, nGetal1 / nGetal2
is carried out. If it's false, nGetal2 / nGetal1
is carried out.
Upvotes: 3