Error Split by 0

Asked

Viewed 988 times

1

Hello

I would like a help, I’m starting with language and I’m having some doubts, What I want in my code is that the division calculation is not divided by zero. The moment I enter the value of Y = 0 returns a message "Invalid, cannot be divided by 0".

When I do an Insert with divisor 0 returns this message:

Calculadora03.rb:32:in `/': divided by 0 (ZeroDivisionError)
        from Calculadora03.rb:32:in `calculo'
        from Calculadora03.rb:57:in `<main>'

This is my code:

def escolha_operador
    puts "Escolha o tipo de operação abaixo:"
    puts "1 Adição"
    puts "2 Subtração"
    puts "3 Multiplicação"
    puts "4 Divisão"
    puts ""

    tipo_operador = gets.chomp().to_i

    if tipo_operador == 1
        return "Adição"
    elsif tipo_operador == 2
        return "Subtração"
    elsif tipo_operador == 3
        return "Multiplicação"
    elsif tipo_operador == 4
        return "Divisão"
    else
        return "erro"
    end
end

def calculo(operacao, x, y)
    if operacao == "Adição"
        return resultado = x + y
    elsif operacao == "Subtração"
        return resultado = x - y
    elsif operacao == "Multiplicação"
        return resultado = x * y
    elsif operacao == "Divisão"
        return resultado = x / y
    end
  # elsif operacao == "Divisão"
    #   rescue ZeroDivisionError
    #   else
    #   return resultado = x / y
  # end
end

continuar = 1

while continuar == 1

  calculo_atual = escolha_operador()

  if calculo_atual == "erro"

    puts "Opção invalido! Escolha a opção correta."

    else
    puts "Entre com o primeiro valor da #{calculo_atual}: "
    p_numero = gets.to_i
    puts "Entre com o segundo valor da #{calculo_atual}: "
    s_numero = gets.to_i

    result = calculo(calculo_atual, p_numero, s_numero)

    puts "O resultado é #{result}"
    puts "Deseja continuar o calculo? Digite 1- Sim ou 2- Não"
    continuar = gets.to_i

        system ('cls')

    if continuar != 1


    end
  end
end
  • 3

    Do you want to subvert mathematics? What would be the result of a number divided by 0?

  • Your question is unclear. Dividing by 0 is an error that was discovered long before the invention of programming languages. Now, if you want to treat the split when the divisor is 0, just do a if rather invoke division. If divisor is 0, do not divide

  • @Amadeus sorry I ended up describing wrong even my doubt. What I want in my code is that the division calculation is not divided by zero. The moment I am putting the value of Y = 0 returns a message "Invalid, cannot be divided by 0".

5 answers

5


As Isaac said, put an IF to the y, should look like this:

elsif operacao == "Divisão"
    if y != 0
        return resultado = x / y
    else
        return "Invalido, não pode ser divido por 0"
    end
end

So this:

result = calculo(calculo_atual, p_numero, s_numero)

puts "O resultado é #{result}"

It’ll display something like:

The result is Invalid, cannot be divided by 0

1

It’s a mathematical rule, nothing can be divided by 0. In any programming language will give error if you try to divide by 0. You can put one if to check that the splitter is not 0.

  • I commented wrong hehe, I do not want in my code, the division calculation is divided by 0.

  • @Cintia and tried to put the IF to check if the divider is 0 as Isaque said?

  • yes @Guilhermenascimento pus. It worked

  • @Cintia what mistake? Same? If it was the same, it’s because you didn’t do IF correctly, it shows how you put that if. See if it works: https://answall.com/a/239444/3635

  • @Guilhermenascimento I only edited my doubt... but I did as you said ...I used the IF and it worked out well

  • @Cintia legal, if it worked, mark my answer or Isaac’s as correct (whichever you prefer)

Show 1 more comment

1

Divisions by zero throw a type exception ZeroDivisionError, that can captured with raise and translated into a Float::NaN (Not A Number), look at you:

def calculo(operacao, x, y)
    if operacao == "Adição"
        return resultado = x + y
    elsif operacao == "Subtração"
        return resultado = x - y
    elsif operacao == "Multiplicação"
        return resultado = x * y
    elsif operacao == "Divisão"
        return resultado = x / y
    end
rescue ZeroDivisionError
    return Float::NAN
end

p calculo("Divisão", 1, 0 )
p calculo("Divisão", 10, 2 )
p calculo("Divisão", 70, 5 )
p calculo("Divisão", 20, -5 )

Exit:

NaN
5
14
-4

Example in repl it.

  • At the time I tried to use this Rescue command, and it wasn’t working.. thanks for the help...

0

Change the code piece for this:

def calculo(operacao, x, y)
if operacao == "Adição"
    return resultado = x + y
elsif operacao == "Subtração"
    return resultado = x - y
elsif operacao == "Multiplicação"
    return resultado = x * y
elsif operacao == "Divisão"
    if y != 0
       return resultado = x / y
    end
end

The problem is that you can’t divide a number by zero. It’s a mathematical rule.

0

As noted above, the mathematical rule precludes division by 0.

So if you want to try to divide some number by 0, you could try the solution

10.try(:/, 0)

where you will get the answer: Zerodivisionerror: divided by 0.

However remembering that good practice should be to check the value before attempting such an operation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.