我写了一个程序。
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)
请帮忙。
答案 0 :(得分:0)
如果使用chomp
将输入字符串转换为整数,则无需to_i
。 PI
中有一个常数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)
错误导致radius
,height
被视为来自终端的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