dimanche 10 novembre 2019

If statement should give int and alert when using 0

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

Aucun commentaire:

Enregistrer un commentaire