加载中...

习题 29: 如果(if)


这里是你接下要写的作业,这段介绍了 if-statement (if 语句)。把这段输入进去,让它能够正确执行。然后我们看看你是否有收获。

  1. people = 20
  2. cats = 30
  3. dogs = 15
  4. if people < cats
  5. puts "Too many cats! The world is doomed!"
  6. end
  7. if people > cats
  8. puts "Not many cats! The world is saved!"
  9. end
  10. if people < dogs
  11. puts "The world is drooled on!"
  12. end
  13. if people > dogs
  14. puts "The world is dry!"
  15. end
  16. dogs += 5
  17. if people >= dogs
  18. puts "People are greater than or equal to dogs."
  19. end
  20. if people <= dogs
  21. puts "People are less than or equal to dogs."
  22. end
  23. if people == dogs
  24. puts "People are dogs."
  25. end

你应该看到的结果

  1. $ ruby ex29.rb
  2. Too many cats! The world is doomed!
  3. The world is dry!
  4. People are greater than or equal to dogs.
  5. People are less than or equal to dogs.
  6. People are dogs.
  7. $

加分习题

猜猜“if 语句”是什么,它有什么用处。在做下一道习题前,试着用自己的话回答下面的问题:

  1. 你认为 if 对于它下一行的程式码做了什么?
  2. 把习题 29 中的其它布林表示式放到“if 语句”中会不会也可以运行呢?试一下。
  3. 如果把变量 people、cats 和 dogs 的初始值改掉,会发生什么事情?

还没有评论.