這里是你接下要寫的作業,這段介紹了 `if-statement` (if 語句)。把這段輸入進去,讓它能夠正確執行。然后我們看看你是否有收獲。
~~~
people = 20
cats = 30
dogs = 15
if people < cats
puts "Too many cats! The world is doomed!"
end
if people > cats
puts "Not many cats! The world is saved!"
end
if people < dogs
puts "The world is drooled on!"
end
if people > dogs
puts "The world is dry!"
end
dogs += 5
if people >= dogs
puts "People are greater than or equal to dogs."
end
if people <= dogs
puts "People are less than or equal to dogs."
end
if people == dogs
puts "People are dogs."
end
~~~
# 你應該看到的結果
* * * * *
~~~
$ ruby ex29.rb
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.
$
~~~
# 加分習題
* * * * *
猜猜「if 語句」是什么,它有什么用處。在做下一道習題前,試著用自己的話回答下面的問題:
1. 你認為 if 對于它下一行的代碼做了什么?
2. 把習題 29 中的其它布爾表達式放到「if 語句」中會不會也可以運行呢?試一下。
3. 如果把變量 people、cats 和 dogs 的初始值改掉,會發生什么事情?
- 笨方法更簡單
- 習題 00: 準備工作
- 習題 01: 第一個程序
- 習題 02: 注釋和#號
- 習題 03: 數字和數學計算
- 習題 04: 變量的命名
- 習題 05: 更多的變量和輸出
- 習題 06: 字符串和文字
- 習題 07: 更多輸出
- 習題 08: 輸出,輸出
- 習題 09: 輸出,輸出,輸出~
- 習題 10: 那是啥?
- 習題 11: 提問
- 習題 12: 模塊
- 習題 13: 參數,解包,參數
- 習題 14: 提示和傳遞
- 習題 15: 讀取文件
- 習題 16: 操作文件
- 習題 17: 更多的文件操作
- 習題 18: 命名,變量,代碼,函數
- 習題 19: 函數和變量
- 習題 20: 函數和文件
- 習題 21: 函數可以傳入信息
- 習題 22: 到現在你學到了什么?
- 習題 23: 閱讀一些代碼
- 習題 24: 更多練習
- 習題 25: 更多更多的練習
- 習題 26: 恭喜你,現在來考試了!
- 習題 27: 記住邏輯關系
- 習題 28: Boolean表達式練習
- 習題 29: 如果
- 習題 30: Else 和 If
- 習題 31: 做出判斷
- 習題 32: 循環和數組
- 習題 33: While
- 習題 34: 存取數組里的元素
- 習題 35: 分支和函數
- 習題 36: 設計和測試
- 習題 37: 重視各種符號