-1

我收到以下错误:

/calcTax.rb:9: syntax error, unexpected $undefined
  grandtotal = $#{subtotal - tax}

从这段代码:

print('What amount would you like to calculate tax for?  $')
subtotal = gets.to_i
taxrate = 0.078
tax = subtotal * taxrate
if (tax > 0.0)
  grandtotal = $#{subtotal + tax}
else if (tax < 0.0)
  grandtotal = $#{subtotal - tax}
puts "Tax on $#{subtotal} is $#{tax}, so the grandtotal is $#{grandtotal}."

我想知道我是否需要以subtotal不同的方式设置一个值,或者我可以做些什么来修复我的程序?

unexpected $end在第 10 行也遇到了错误。

4

1 回答 1

1

您的语法有一些问题。

首先,$#{blah}仅在将变量插入带引号的字符串时才需要(并且仅有效!)语法。当您只是执行计算时,您可以简单地说:

grandtotal = subtotal + tax

您还需要then在两行末尾添加一个if,更改else ifelsif,并end在第二grandtotal行之后添加一个。完成这项工作后,您应该拥有:

print('What amount would you like to calculate tax for?  $')
subtotal = gets.to_i
taxrate = 0.078
tax = subtotal * taxrate
if tax > 0.0 then
  grandtotal = subtotal + tax
elsif tax < 0.0 then
  grandtotal = subtotal - tax
end
puts "Tax on $#{subtotal} is $#{tax}, so the grandtotal is $#{grandtotal}."

这似乎有效。

于 2012-09-10T04:02:53.153 回答