-1
def percent_of
puts "What is the number?"
number = gets.chomp.to_f
puts "What is the percent?"
percent = gets.chomp.to_f
total_percent_of = number * percent.to_f
puts " #{percent}% of #{number} is #{total_percent_of.to_i}."
end
好吧,這是一個非常簡單的程序百分比,工作正常。但有一件事我不喜歡的是,每當控制檯打印出總數時,它看起來像下面的例子:417的75.0%是31275. 現在有什麼辦法可以讓我用十進制/錢形式輸入總數?就像它應該是312.75或類似的東西。請儘量保持你的答案簡單,我是Ruby的新手。謝謝!打印號碼時的金額格式
謝謝!現在效果很好。 – zappdapper 2014-09-12 13:37:28
如果您要使用格式字符串,則將其用於所有變量。不要將它們混淆,因爲這會變得更難以閱讀/維護:'sprintf「%d %%%d是%.2f」,[percent,number,total_percent_of]' – 2014-09-12 16:48:55
我實際上更喜歡'puts「#{因爲它將字符串格式化本地化爲唯一需要它的地方,所以#{number}的%}%是#{'%。2f'%total_percent_of}「。 – Max 2014-09-12 17:03:11