Ruby数学计算器程序

时间:2013-04-23 00:47:27

标签: ruby user-input gets

我写了一个程序。

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 个答案:

答案 0 :(得分:0)

如果使用chomp将输入字符串转换为整数,则无需to_iPI中有一个常数Math

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)

答案 1 :(得分: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个字符串不能相乘。为了使这个可行,请执行:

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