domingo, 12 de fevereiro de 2023

Operações Matemáticas em Javascript


Operações Matemáticas Básicas
Adição: uso de +
console.log(2 + 4)

Subtração: uso de -
console.log(8 - 4)

Multiplicação: uso de *
console.log(2 * 4)

Divisão: uso de /
console.log(650 / 25)

Potência: uso de **
console.log(2 ** 5) // 2^5 = 2*2*2*2*2 = 32

Modulo/Remainder: uso de %
console.log(5 % 2) / * 5/2 = 2.5 5-2*2 = 1 --> 5%2 = 1 * /
Arredondando Resultados
Math.floor() é um método que arredonda um número para baixo, retornando o resultado.
Math.ceil() é um método que arredonda um número para cima, retornando o resultado.
Math.random () garante um número aleatório, dada a quantidade fornecida.
Math.random() * 3

Exemplo de código que escolhe um número entre 0 e 3 e o arredonda para que não fique decimal:
Math.floor(Math.random() * 3)


You can easily increment or add one to a variable with the ++ operator. i++; is the equivalent of i = i + 1; Note: The entire line becomes i++;, eliminating the need for the equal sign. You can easily decrement or decrease a variable by one with the -- operator. i--; is the equivalent of i = i - 1; Note: The entire line becomes i--;, eliminating the need for the equal sign. Remainder % gives the remainder of the division of two numbers. Example 5 % 2 = 1 because Math.floor(5 / 2) = 2 (Quotient) 2 * 2 = 4 5 - 4 = 1 (Remainder) Usage In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by 2. 17 % 2 = 1 (17 is Odd) 48 % 2 = 0 (48 is Even) Note: The remainder operator is sometimes incorrectly referred to as the modulus operator. It is very similar to modulus, but does not work properly with negative numbers. Compound Assignment With Augmented Addition In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say: myVar = myVar + 5; to add 5 to myVar. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step. One such operator is the += operator. let myVar = 1; myVar += 5; console.log(myVar); 6 would be displayed in the console. Compound Assignment With Augmented Subtraction Like the += operator, -= subtracts a number from a variable. myVar = myVar - 5; will subtract 5 from myVar. This can be rewritten as: myVar -= 5; Compound Assignment With Augmented Multiplication The *= operator multiplies a variable by a number. myVar = myVar * 5; will multiply myVar by 5. This can be rewritten as: myVar *= 5;