【问题标题】:currency converter in ruby [closed]红宝石中的货币转换器[关闭]
【发布时间】:2013-11-12 21:39:00
【问题描述】:

创建转换器的工作已经拖了几个小时。它应该从一种货币转换为另一种货币 这是代码:

def converter   
  puts "Enter the amount you wish to convert"  
  userAmount = gets   
  puts "Enter your choice: 1 for converting Qatari
  Riyals to US Dollars"   
  puts "Enter your choice: 2 for converting USD ollars to Qatari Riyals"   
  choiceConvert = gets
  while choiceConvert != 1 || choiceConvert != 2 do
    puts "please enter either 1 or 2"
    choiceConvertNew = gets
    choiceConvert = choiceConvertNew   
  end
  if choiceConvert == 1
    convertedAmount = userAmount / 3.65
    puts "Your choice is to convert #{userAmount} Qatari Riyals to US Dollars; 
      You get #{convertedAmount}  US Dollars" 
   else 
     convertedAmount = userAmount * 3.65
     puts "Your choice is to convert #{userAmount} US Dollars to Qatari Riyals; 
       You get #{convertedAmount} Qatari Riyals"  
   end    
end

converter

【问题讨论】:

  • 你面临的问题是什么?
  • gets 更改为gets.to_i 将是一个好的开始。 gets 的返回值为String,包括用户按回车的\n
  • 要修复代码的格式,单击{} 图标突出显示它。一种 Ruby 约定是对类和模块名称使用“驼峰式”(例如,MyClass),对变量和方法名称使用小写(例如,choice_convert)。正如@Ivaylo 所说,您需要明确说明您遇到的问题。如果您在运行代码时收到错误消息,则应说明错误及其发生位置。通常,包含一个简单的示例会很有帮助,该示例显示您对给定输入的期望输出,以及您得到的结果。
  • 您使用gets 几次从stdin 获取输入。如果 Ruby 执行str = gets,它将等待输入。如果您输入"3.56"(后跟回车或回车),str 将设置为等于"3.57\n"。如果您不想要换行符(通常是这种情况),请将语句更改为str = gets.chomp。那么str 将是"3.57"。如果你想把它当作一个浮点数,为了在计算中使用它,把它改成val = gets.chomp.to_f,这样val就等于3.57。实际上,Ruby 足够聪明,您只需输入val = gets.to_f

标签: ruby operators converter currency


【解决方案1】:

你想在一个地方做很多事情试试这个

def convert_currency(amount,choice)
  converted_amount = choice == 1 ? amount / 3.65 : amount * 3.65
  from, to = choice == 1 ? ["Qatari Riyals", "US Dollars"] : ["US Dollars","Qatari Riyals"]
  puts "Your choice is to convert #{sprintf('%.2f',amount)} #{from} to #{to}; You get #{sprintf('%.2f',converted_amount)} #{to}"
end

puts "Please Enter an Amount"
user_amount = gets.to_f
choice_convert = nil
while ![1,2].include?(choice_convert)
  puts "Enter your choice: 1 for converting Qatari Riyals to US Dollars"
  puts "Enter your choice: 2 for converting US Dollars to Qatari Riyals"
  choice_convert = gets.to_i
end
convert_currency(user_amount,choice_convert)

【讨论】:

  • 仅供参考,如果您在gets 上使用.to_i.to_f,则不需要.chomp.to_i.to_f 将去掉换行符。
  • 谢谢,我不会为这样的用户输入编写太多代码。(编辑后的帖子)
猜你喜欢
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多