如何使put输出读取实际数字,而不是(x,y)

  • 本文关键字:数字 put 何使 输出 读取 ruby
  • 更新时间 :
  • 英文 :


所以我编写的程序可以工作,但当我得到输出时,它说,点x,y位于"插入端";。我需要更改什么才能获得";x、 y";给出输入的数字?

puts "Enter the x and y coordinate points:"
x = gets.chomp.to_f
y = gets.chomp.to_f
if x > 0 and y > 0
puts "point #{"x,y"} lies in the First quadrant"
elsif x < 0 and y > 0
puts "point #{"x,y"} lies in the Second quadrant"
elsif x < 0 and y < 0
puts "point #{"x,y"} lies in the Third quadrant"
elsif x > 0 and y < 0
puts "point #{"x,y"} lies in the Fourth quadrant"
elsif x == 0 and y > 0
puts "point #{"x,y"} lies at the positive y axis"
elsif x == 0 and y < 0
puts "point #{"x,y"} lies at the negative y axis"
elsif y == 0 and x < 0
puts "point #{"x,y"} lies at the negative x axis"
elsif y == 0 and x > 0
puts "point #{"x,y"} lies at the positive x axis"
else
puts "point #{"x,y"} lies at the origin"
end    

使用两个#{}构造(每个变量一个(来插值两个变量,如下所示:

puts "point #{x},#{y} lies in the first quadrant"

CCD_ 2简单地插入字符串"0";x、 y";插入字符串,这不是你想要的。

用一个#{}将两个变量插入到字符串中是可能的,但这有点冗长,因为xy是浮点值,所以必须调用to_s两次。它们不能与','按原样连接,因为Ruby会尝试将字符串转换为浮点值,然后抱怨它不能。

puts "point #{x.to_s + ',' + y.to_s} lies in the first quadrant"

如前所述,"#{value}"插值,而您的值是文字";x、 y";这就是为什么你会得到你所做的结果。如果你想更多地控制值的格式,你可以这样做:

formatted_point = "point %.1f, %.1f" % [x,y]

然后像这样使用。

puts "#{formatted_point} lies in the First quadrant"

你可以在这里找到字符串格式的所有细节

最新更新