这是我的代码:
print('What amount would you like to calculate tax for? ')
subtotal = gets.chomp
taxrate = 0.078
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so the grand total is $#{subtotal + tax}."
第一个输出:What amount would you like to calculate tax for?
输入:100
。
最终输出:Tax on $100 is $, so the grand total is $100.
我相信我应该获得$7.79999999
的税率和107.7999999
的总额。如果用户错误地输入$,并且四舍五入到最接近的分数,我想通过执行诸如从输入中删除$等操作来使代码更好一点。首先,我需要理解为什么我没有得到任何输出或添加,对吧?
让我们来看看你的代码:
subtotal = gets.chomp
gets.chomp
给你一个字符串所以这个:
tax = subtotal * taxrate
使用String#*
而不是乘以数字:
str * integer→new_str
复制 - 返回包含接收器整数副本的新
String
。
但是taxrate.to_i
会给你零,而any_string * 0
会给你一个空字符串。所以你得到的正是你所要求的,你只是在问错了。
subtotal = gets.to_f # Or gets.to_i
如果你使用chomp
或to_i
,你将不需要to_f
,这些方法将忽略它们自己的尾随空格。
这应该会给你一个合理的价值在tax
。