-3
Good afternoon, I have a problem where I can’t get the final result. The program is as follows: the user will enter the values, the operation you want (sum or subtraction), and the program will perform the rest.
I am learning function, and so I would like to perform this calculation using functions (sum and subtraction) within another main function (calculation). From now on, thank you!
var n1 = prompt('Digite o primeiro número:')
var n2 = prompt('Digite o segundo número:')
n1 = parseInt(n1)
n2 = parseInt(n2)
var operacao = prompt('Digite a operação que você deseja(soma ou subtração)')
function calculo(n1,n2, operacao){
if (operacao == 'soma') {
callbackSoma(n1,n2)
}else if(operacao == 'subtracao') {
callbackSubtracao(n1,n2)
}else{
document.write('Digite uma operação válida')
}
}
function callbackSoma(n1,n2){
return resultado = n1+n2
}
function callbackSubtracao(n1,n2){
return resultado = n1-n2
}
document.write('o resultado final foi de: ' +calculo(n1,n2,operacao))
Inside the callbackEtc functions you only need to return the value. Ex:
return n1+n2
(instead ofreturn resultado = n1+n2
, which is unnecessary), and in functioncalculo
you need to return too:return callbackSoma(n1,n2)
instead of justcallbackSoma(n1,n2)
. And put a semicolon at the end of the lines. It may seem "fresh", but it avoids some bizarre situations that may occur if you don’t use them, such as that one and that one (see more about this here).– hkotsubo
to yes, thank you very much!
– lRoque