Ruby数学计算器程序

Ruby数学计算器程序,ruby,user-input,gets,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”是我输入的圆柱体半径/高度): 请提供帮助。如果您使用to_i将输入字符串转换为整数,则无需chomp。在Math中有一个常数PI print

我写了一个程序

print "Radius = "
radius = gets.chomp

print "Height = "
height = gets.chomp

ans = (2 * 3.14 * (radius * radius)) + (2 * 3.14 * radius * height)
这行不通。这是终端中的输出(
“11”
“10”
是我输入的圆柱体半径/高度):


请提供帮助。

如果您使用
to_i
将输入字符串转换为整数,则无需
chomp
。在
Math
中有一个常数
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)

错误原因为
半径
高度
从终端取为
字符串
。请看下面:

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)
输出:

因此,两个字符串不能相乘。要使其可行,请执行以下操作:

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 = "
11
String
"Height = "
12
String
 `*': can't convert String into Integer (TypeError)
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