Prog in C stating if x is divisible

Asked

Viewed 42 times

0

Good afternoon guys, all right?

I’m continuing my C exercises, and I got stuck in one more. Here is the statement of the same:

Write an algorithm that takes a keyboard number and tells you if it is divisible by 8, by 5, by 2 or if it is not divisible by any of these. Check for each of the numbers. Example: Number: 8 Divisible by 8 Divisible by 2

My code:

inicio

      escreva("Digite um número: ")
      leia(num)

      d2 <- (num%2)
      d5 <- (num%5)
      d8 <- (num%8)

      soma <- d2+d5+d8

      se (soma = 0) entao
         escreval("Número não é divisível por nenhuma das opções (2, 4 e 5)")
      senao
           se (d2 = 0) entao
              escreval("Número divisível por 2")
           senao
                se (d5 = 0) entao
                   escreval("Número divisível por 5")
                senao
                     se (d8 = 0) entao
                        escreval("Número divisível por 8")
                     fimse
                fimse
           fimse
      fimse

fimalgoritmo

Only, it only if I type "8" for example, it says it is divisible only by 2. And when I type 40, it said it is not divisible by any of the options.

Can someone help me with this?

1 answer

1

There are two problems with this algorithm. The first problem is related to the first se:

se (soma = 0) entao

When the sum is zero, it means that it is divisible by all and not that it is not divisible by any.

The second problem is related to the entanglement of the if/senao. For example, when you say that:

se (d2 = 0) entao
    escreval("Número divisível por 2")
senao

This you are saying, enter this if, if anything happens, else do it. However, the se/senao should only be used when one condition influences the other, which is not the case in that situation. the fact that it is divisible by 2 does not make it divisible by 5 or 8, so these seshould not be nested.

  • So, about the first se I must use se (soma <> 0) entao? And in relation to the interweaving of se/senao I shouldn’t use the senao and yes the fimse according to each repeat opening?

  • I made the changes, and really now he’s telling it right by which the one is divisible, straight. However, he’s printing the se (soma<>0) entao in all cases.

  • I returned the first se for what was first: se (soma=0) entao and it is running correctly. The only one however is the number 80, which is printed ALL messages from se.

  • @Tspereirarj it rotates all messages from se, porque todos dividem o número, tem várias formas de resolver, a ideal seria ir "juntando" a string conforme fosse tendo as divisões. Por exemplo, entrou no senão (é divisível por algum número), faz o seguinte: res <- "this number is divisible by: "e ir concantenando por quem é divisível nessa variável res e dar um` in it at the end.

Browser other questions tagged

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