2013-11-01 115 views
-3

與我創建轉換器的工作一直在拖延幾個小時。它應該從一種貨幣轉換爲另 這是代碼:ruby​​中的貨幣轉換器

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 
+3

,什麼是你所面臨的問題? –

+2

將'gets'改爲'gets.to_i'將是一個好的開始。 'gets'的返回值是一個'String',包括用戶按下Enter的'\ n'。 –

+0

要修正代碼的格式,請點擊「{}」圖標突出顯示它。一個Ruby約定是對類和模塊名稱(例如'MyClass')使用'camel-case',對變量和方法名稱使用小寫(例如'choice_convert')。正如@Ivaylo所說,你需要明確你所遇到的問題。如果您在運行代碼時收到錯誤消息,則應說明錯誤及其發生的位置。通常包含一個簡單的示例會很有幫助,該示例顯示了您對給定輸入的期望輸出以及您正在獲取的內容。 –

回答

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) 
+0

僅供參考,如果您在'gets'上使用'.to_i'和'.to_f',則不需要'.chomp'。 '.to_i'和'.to_f'將會去掉換行符。 –

+0

謝謝我不寫這麼多的用戶輸入代碼。(Editted Post) – engineersmnky