2012-09-09 47 views
0

这是我的代码:我的打印/获取或输出错误的类型?

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。我希望通过执行诸如从输入中剥离$,如果用户错误地输入$,并四舍五入到最接近的分数来使代码更好一些。首先,我需要理解为什么我没有得到任何输出或补充,但是,对吗?

回答

1

让我们通过代码:

subtotal = gets.chomp 

gets.chomp给你一个字符串所以这个:

tax = subtotal * taxrate 

使用String#*而不是乘号:

海峡*整数→new_str

复制 - 返回新的String包含整数接收器的副本。

但是taxrate.to_i会给你零和any_string * 0给你一个空字符串。所以你得到了你要求的东西,你只是要求错误的东西。

您需要subtotal转换为数字与to_ito_f

subtotal = gets.to_f # Or gets.to_i 

你不会需要chomp如果使用to_ito_f,这些方法会忽略自己的尾随空白。

这应该给你一个合理的价值tax

+0

+0

@ Wolfpack'08:你在说什么? –

+0

基本上,'taxrate = gets.to_i'返回一个整数,从而产生正确的输出。在整数的末尾没有添加直觉/'几乎不需要'的换行符,就像在字符串中一样。 –