2014-09-12 100 views
-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的新手。謝謝!打印號碼時的金額格式

回答

1

首先你需要修復你的數學。 75%等於75/100所以你要

total_percent_of = number * percent/100.0 

接下來,您需要一個格式字符串,以確保total_percent_of總是印有正確的小數位數的:

sprintf " #{percent}%% of #{number} is %.2f", total_percent_of 

(你需要的%%因爲百分號對sprintf有特殊含義percent)。有關字符串格式的更多信息,請參閱the documentation

+0

謝謝!現在效果很好。 – zappdapper 2014-09-12 13:37:28

+0

如果您要使用格式字符串,則將其用於所有變量。不要將它們混淆,因爲這會變得更難以閱讀/維護:'sprintf「%d %%%d是%.2f」,[percent,number,total_percent_of]' – 2014-09-12 16:48:55

+0

我實際上更喜歡'puts「#{因爲它將字符串格式化本地化爲唯一需要它的地方,所以#{number}的%}%是#{'%。2f'%total_percent_of}「。 – Max 2014-09-12 17:03:11