Home > Enterprise >  I want to know how to make this calculation
I want to know how to make this calculation

Time:08-28

please Im trying to solde this algorithm but Im not sur I did the correct thing. I need your help thanks

Implement a calculation respecting the following rules (assume that the numbers received are positive integers greater than zero):  

  • Calculates the sum of the numbers received as parameter.

  • For each number that is a multiple of 3, add 1 to that number.

    function Calculator(numbers) {

      let sum=0;
      for(let num of numbers){
          if(num % 3 == 0) {
              sum =num   1
          }
          else {
              sum =num;
          }
      }
      return 0;
    

    }

CodePudding user response:

const nums = [3, 6, 7, 9, 13, 22, 27]

const calculator = (numbers) => {

  let sum = 0;
  for (let num of numbers) {
    if (num % 3 == 0) {
      num  
      sum  = num; 
    }
    else {
      sum  = num;
    }
  }
  return sum //you forgot to return your sum but rather you return always zero.
}

console.log(calculator(nums))

CodePudding user response:

You can also do something like the following using ternary operator:

const numbers = [3, 6, 7]

function calculate(arr){
  let total = 0
  for (let n of arr) {
    n % 3 === 0 ? total  = n   1 : total  = n
  }
  return total
}

console.log(calculate(numbers))

  • Related