2015-07-10 15 views
1

我試圖通過gets.chomp添加用戶輸入的總成本,然後將其放回函數中,以便在函數結束時打印出總成本。我做對了嗎?如何將變量打印回我的函數?

def costs_of_company(hosting, design, phones, total_costs) 
    puts "Total costs are as follows: \n" 
    puts "Hosting costs $#{hosting}." 
    puts "Design would cost $#{design}." 
    puts "The cost for 100 Phones would be $#{phones}." 
    puts "Total costs are #{total_costs}" 
end 

puts "Tell me the costs of your company. \n" 
puts "hosting \n" 
hosting = gets.chomp 
puts "design \n" 
design = gets.chomp 
puts "phones \n" 
phones = gets.chomp 
total_costs = hosting + design + phones #I think i am way off here. 

costs_of_company(hosting, design, phones) 
+0

我相信你忘了在'total_costs'變量傳遞到costs_of_company'的'你的函數調用在最後一行 – Dbz

回答

1

total_costs = hosting + design + phones的問題是輸入是字符串格式。這將工作,如果你沒有total_costs = hosting.to_i + design.to_i + phones.to_i

這是假設所有輸入都是整數。或者,如果要使用小數(浮點數),則使用.to_f

此外,你也可以做hosting = gets.chomp.to_idesign = gets.chomp.to_i,並phones = gets.chomp.to_i

然而,現在我們進入我們怎麼知道的境界,如果用戶給了我們很好的輸入?如果輸入不是整數,例如.to_i的默認行爲是默認爲零。 "hello".to_i == 0。對大多數情況來說這很好。

更復雜的方法是創建一個處理用戶輸入的函數,以便您可以在一個地方清理所有內容,並處理錯誤。例如,如果您想使用Integer()而不是.to_i,則需要捕獲錯誤,因爲使用整數對無效輸入引發異常。下面是使用正則表達式來處理輸入異常的例子。

def get_input 
    while true 
    begin 
     input = gets.chomp.match(/d+/)[0] 
    rescue Exception => e 
     puts "that is not a valid integer. Please try again" 
    else 
     return input 
    end 
    end 
end 
+0

非常感謝您的深入細分和分析。我將研究你已經概述並推進的事情。 – codedownforwhat

+0

沒問題!如果這是您正在尋找的答案,請確保在投票箭頭下點擊複選標記。 – Dbz

0

我會使用.to_f來追蹤錢幣並將其打印得更漂亮。這裏有一個調試版本:

def print_money(val) 
    format('%.2f',val) 
end 

def costs_of_company(hosting, design, phones) 
    puts "Total costs are as follows: \n" 
    puts "Hosting costs $#{print_money(hosting)}." 
    puts "Design would cost $#{print_money(design)}." 
    puts "The cost for 100 Phones would be $#{print_money(phones)}." 
    total_costs = hosting + design + phones 
    puts "Total costs are $#{print_money(total_costs)}" 
end 

puts "Tell me the costs of your company. \n" 
puts "hosting \n" 
hosting = gets.chomp.to_f 
puts "design \n" 
design = gets.chomp.to_f 
puts "phones \n" 
phones = gets.chomp.to_f 

costs_of_company(hosting, design, phones) 
+0

def print_money(val) format('%2f',val) end 這個函數發生了什麼。 %.2f是那個浮點數? – codedownforwhat