我的打印/接收或输出错误的类型?

问题描述 投票:0回答:1

这是我的代码:

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的总额。如果用户错误地输入$,并且四舍五入到最接近的分数,我想通过执行诸如从输入中删除$等操作来使代码更好一点。首先,我需要理解为什么我没有得到任何输出或添加,对吧?

ruby types syntax casting
1个回答
1
投票

让我们来看看你的代码:

subtotal = gets.chomp

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

tax = subtotal * taxrate

使用String#*而不是乘以数字:

str * integer→new_str

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

但是taxrate.to_i会给你零,而any_string * 0会给你一个空字符串。所以你得到的正是你所要求的,你只是在问错了。

您需要将subtotal转换为to_ito_f中的数字:

subtotal = gets.to_f # Or gets.to_i

如果你使用chompto_i,你将不需要to_f,这些方法将忽略它们自己的尾随空格。

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

© www.soinside.com 2019 - 2024. All rights reserved.