0

我写了一个程序。

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)

请帮忙。

4

2 回答 2

0

chomp如果您使用 . 将输入字符串转换为整数,则无需这样做to_i。并且有一个常数PIMath

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)
于 2013-04-23T01:08:14.533 回答
0

错误导致 asradius并被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
于 2013-04-23T07:25:23.443 回答