puts "Quel age tu as ?"
print ">"
age = gets.chomp.to_i
i = 0
while age > 0
puts "Il y a " age.to_s " ans" " tu avais : " i.to_s " ans"
age -= 1
i = 1
break if age = i
puts "Il y a " age.to_s " ans" " tu avais la moitié de ton age !"
age = i
end
我在 Ruby On Rails 上的程式有問題。我提前為我的英語道歉。
我通過做一個練習來訓練這門語言,讓你輸入你的年齡,看看你在特定年份的年齡。
但例如。當我們達到一半年齡時,例如 20 歲,我想展示(法語)
“十年前,你只有一半的年齡!”
我想感謝“break if”,但這只會產生一行代碼。我希望你已經理解,否則不要猶豫,要求澄清。
先感謝您。
uj5u.com熱心網友回復:
break不一定需要是單行break,在滿足條件后您可以自己擁有所有內容,而且您的代碼中存在問題,您正在與 an=而不是 a進行比較==
if (condition == true)
break
end
你的代碼可能看起來像
puts "Quel age tu as ?"
print ">"
age = gets.chomp.to_i
i = 0
while age > 0
puts "Il y a " age.to_s " ans tu avais : " i.to_s " ans"
age -= 1
i = 1
if age == i
puts "Il y a " age.to_s " ans tu avais la moitié de ton age !"
break
end
end
注意:我還可以指出,"Ten years ago, you were half your age!"如果輸入的年齡是奇數,您的代碼將不會顯示
uj5u.com熱心網友回復:
一條break陳述句停止您的 while 回圈。你可能想要一個if運算式:
while age > 0
if age == i
puts "Il y a #{age} ans tu avais la moitié de ton age !"
else
puts "Il y a #{age} ans tu avais : #{i} ans"
end
age -= 1
i = 1
end
downto您可以使用and擺脫手動遞增/遞減with_index:
age.downto(1).with_index do |a, i|
if a == i
puts "Il y a #{a} ans tu avais la moitié de ton age !"
else
puts "Il y a #{a} ans tu avais : #{i} ans"
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416224.html
標籤:
上一篇:紅寶石|如何轉換郵件之類的數字?
