开发者

And and Or logic reversed in basic while loop

开发者 https://www.devze.com 2023-03-14 17:02 出处:网络
I\'ve just started use rails but this logic seems reversed to me. weight = 70 num_pallets = 25 while weight < 100 and num_pallets <=30

I've just started use rails but this logic seems reversed to me.

weight = 70
num_pallets = 25
while weight < 100 and num_pallets <=30
    weight += 1
    num_pallets += 1
    puts weight
end

I f开发者_如何学Pythoneel since the loop is supposed to run while both criteria are met the output should run up to 100 for weight. HOWEVER...

When I use and the output is 70 71 72 73 74 75, 76
when I use "or" in place of "and" the output is 70, 71 ... 100

Can anyone explain why this is happening?


while weight < 100 and num_pallets <=30

will run until either weight >= 100 or num_pallets > 30 because that will make the statement false

while weight < 100 or num_pallets <=30

will run until both weight >= 100 and num_pallets > 30 are true as that will make the statement false.


There's a trick to analyzing this.

while weight < 100 and num_pallets <=30
    weight += 1
    num_pallets += 1
    puts weight
end

At the end the opposite will be true.

weight >= 100 or num_pallets > 30

Many folks do this kind of logic in reverse.

  1. Write down what should be true at the end of the loop.

  2. Write down the logical inverse of that condition.

  3. Use the inverse condition for the while.

There's more to it than this, but it should get you started.


and returns true if both of the operands are true.

In your case, num_pallets is 31 after 6 iterations, resulting in a false second expression, thus the whole expression returns false.

or returns true if either of the operands is true. In the first 6 iterations, both expressions are true (weight is below 100 and num_pallets is below or equal 30). In the seventh iteration, num_pallets is 31, thus the second expression is false, but weight is still below 100, so the loop runs until weight is larger than 100.


the loop is supposed to run while both criteria are met - correct.

SO, if one of the criteria fails the loop will stop.


As written, this loop will only execute 5 times because your while statement currently requires BOTH statements to be true. Consequently, because num_pallets begins at 25 and ends at 30, this loop will only execute 5 times. However, if you change the line to read:

weight, num_pallets = 70, 25
while weight < 100 || num_pallets <=30    #Changed to "OR"
  weight, num_pallets = weight + 1, num_pallets + 1
  puts weight
end

... it will run 30 times. Note that the only meaningful change above is the change from AND to OR in the while line.

0

精彩评论

暂无评论...
验证码 换一张
取 消