简体   繁体   中英

how to create three random numbers in javascript and then tell input is odd or not?

如何在javascript中创建三个随机数,然后判断输入是否为奇数?

To determine if odd:

num % 2;

That will return 0 or 1. If you want it to return true or false, then do

(num % 2) == 1;

Make a "isOdd" function and you can use it to check your random numbers against:

function isOdd(num) {
    return (num % 2) == 1;
}

Use it like

function randomizer() {
    var a = Math.floor((Math.random() * 10));
    var b = Math.floor((Math.random() * 10));
    var c = Math.floor((Math.random() * 10));
    if (isOdd(a)) {
    \\Give more points because it's odd
    }
}

Here's a very simple working example: https://codepen.io/anon/pen/rqLVxM

to verify that all numbers are even use this function

function areEven(a,b,c){
 return a%2==0 && b%2==0 && c%2==0 
}

to verify that all numbers are odd use this function

function areOdd(a,b,c){
 return a%2!=0 && b%2!=0 && c%2!=0 
}

to verify that all numbers are are in sequence use this function :

 function areInSequence(a,b,c){
  var array = [a,b,c];
  array.sort(function(a, b){return a - b});
  var validity=false;
  var i;
  var length = array.length
  for (i =0; i < length-1 ; i++) {
      if((array [i+1] - array [i]) == 1){
        validity=true;
      }else validity=false;
  }
  return validity;
}

combine this functions in your code and if you need help leave a comment thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM