2014-07-19 76 views
1

我編程的計算器:爲什麼我的BigDecimal計算器不能輸出正確的值?

require 'bigdecimal' 

def addition() 
    print "Enter the first number " 
    number1 = BigDecimal(gets.chomp) 
    print "Enter the second number " 
    number2 = BigDecimal(gets.chomp) 
    sum = number1 + number2 
    print sum 
end 

它不給予正確的總和。如果我輸入4.21作爲第一位,2.11我輸入0.632E1。如果我輸入4.21作爲第一位,2.11我輸入0.632E1

請幫忙。

回答

4

那個總數是正確0.632E1表示爲6.32。

要想得到一個較爲 「正常」 找數:

# BigDecimal built-in conversion to String 
sum.to_s('F') 

正如BigDecimal documentation for .to_s

所示。你也可以使用:

# Converts to Float, you would lose precision for display, but at least you get 
# the normal expected behaviour of a Float 
sum.to_f 

# Converts to String with known precision (technically this just goes via Float) 
sprintf('%.4f', sum) 
相關問題