简体   繁体   中英

Javascript: Keep count of even and odd random numbers and get the sum of each

When I run this program I am only getting the even number count and the odd sum. The odd count and even sum just gives me 0 every time. Does anyone have any idea what I am missing? Thanks!

I am trying to generate 100 random numbers and keep count of the evens/odds and then get the sum of each.

var min = 1;
var max = 1000;
var randomNumArray = []
var oddCount = []
var evenCount = []
var oddSum = []
var evenSum = []

function isEven(x){
    if (x % 2 == 0)
        return true;
    else
        return false;
}

function sumOfArray(evenSum){
    for(i = 0; i< evenSum.length; i++){
        if (isEven){
            return(evenSum);
        }
        else{
        return (oddSum);
        }
    }
}
for( i = 0; i < 100; i++){
    var randNumber = Math.floor(min + (Math.random() * max));
    randomNumArray.push(randNumber);
}

for( i = 0; i< randNumber.length; i++){
    if (isEven(evenCount[i])){
        return evenCount;
    }
    else{
        return oddCount;
    }
}

console.log('Even Number Count: ' + evenCount);
console.log('Odd Number Count: ' + oddCount);
console.log('Sum Even: ' + evenSum);
console.log('Sum Odd: ' + oddSum);

我只会使用 1 函数来检查它是偶数还是奇数,然后决定将总和与数字本身相加,并将计数加 1。您使它变得更加复杂,我想知道为什么要使用数组。

Try something like this:

for( i = 0; i < 100; i++){
  var randNumber = Math.floor(min + (Math.random() * max));
  if(isEven(randNum)){
     evenSum = evensum+randNum;
     evenCount ++;
  }else{
     oddSum= oddSum+randNum;
     oddSum++;
  }
}
var oddCount = 0
var evenCount = 0
for(i=0; i<randomNumArray.length; i++) {
    if(randomNumArray[i] % 2 == 0) {
        evenCount++
    } else {
        oddCount++
    }
};

Something like that should work?

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