2013-04-23 38 views
0

我寫了一個程序。Ruby數學計算器程序

print "Radius = " 
radius = gets.chomp 

print "Height = " 
height = gets.chomp 

ans = (2 * 3.14 * (radius * radius)) + (2 * 3.14 * radius * height) 

它不起作用。這是在終端輸出("11""10"是什麼,我把爲圓柱的半徑/高):

Radius = 11 
Height = 10 
in `*': can't convert String into Integer (TypeError) 

請幫助。

+2

「無法將字符串轉換爲整數」強烈建議您**需要將「半徑」和「高度」轉換爲數字。 – 2013-04-23 00:51:13

回答

0

如果使用to_i將輸入字符串轉換爲整數,則不需要chompMath中有一個常量PI

print "Radius = " 
radius = gets.to_i 

print "Height = " 
height = gets.to_i 

ans = (2 * Math::PI * (radius * radius)) + (2 * Math::PI * radius * height) 

puts "Answer: #{ans}" 

也知道作爲

ans = 2 * Math::PI * radius * (radius + height) 
0

該錯誤將導致作爲radiusheight被取爲String從終端。看下面:

p "Radius = " 
radius = gets.chomp 
p radius.class 
p "Height = " 
height = gets.chomp 
p radius.class 
p ans = (2 * 3.14 * (radius * radius)) + (2 * 3.14 * radius * height) 

輸出:

"Radius = " 
11 
String 
"Height = " 
12 
String 
`*': can't convert String into Integer (TypeError) 

所以2串不能multiplied.To使這個可行的,這樣做:

p "Radius = " 
radius = gets.chomp.to_i #// or gets.to_i 
p "Height = " 
height = gets.chomp.to_i #// or gets.to_i 
p ans = (2 * 3.14 * (radius * radius)) + (2 * 3.14 * radius * height) 

輸出:

"Radius = " 
12 
"Height = " 
11 
1733.2800000000002