【问题标题】:Ruby : get more then one decimal zero?红宝石:得到多于一位小数零?
【发布时间】:2014-04-26 10:53:17
【问题描述】:

我的代码:

def cube_root(x)
  a = x**(1/3.0)
  p = a.ceil
  puts p
end
gets.chomp.to_i.times do 
    q = gets.chomp.to_i
    cube_root(q)
end

input 2 8 1000

output 2.0 10.0

预期输出 2.0000000000 10.0000000000

【问题讨论】:

  • 我相信你能够比这更好地缩进你的代码。

标签: ruby-2.0 cubes


【解决方案1】:

如果您只想打印额外的小数位,可以尝试:

puts "%.8f" %p

sprintf "%.8f" %p

其中 8 表示小数点后八位。

【讨论】:

  • 如果输入为 2,则输出必须为 1.2599210498
  • 在您的代码中,您调用“ceil”,它将返回一个整数,如果您想获得 n 位小数,您应该使用“round”
猜你喜欢
  • 1970-01-01
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
相关资源
最近更新 更多