gpt4 book ai didi

ruby - 修改多小数点数组,秒转分

转载 作者:太空宇宙 更新时间:2023-11-03 16:42:27 24 4
gpt4 key购买 nike

我正在从文本文件或复制/粘贴到终端中输入一组数字。下面的复制/粘贴示例:

2.552789
2.919615
3.542125
4.212462
5.261249
6.320953

等等。这些数字都用一行分隔,并且都遵循这种格式seconds.hundredths of a second

我将数字列表输入数组并使用以下方法四舍五入到小数点后两位:

while
input != " "
array.push 0.0 + input.to_f.round(2)
input = gets.chomp
end

file_to_open = gets.chomp
array = File.open(file_to_open).readlines.each do |line|
input = file_to_open
while
input != ''
array.push 0.0 + input.to_f.round(2)
input = gets.chomp
end

我还让脚本使用以下方法从数组中选择每第 4 个项目:

module Enumerable
def every_nth(n)
(0... self.length).select{ |x| x%n == n-1 }.map { |y| self[y] }
end
end

最后,我使用一个 block 在每个数字前添加一个“0.”

array = array.map! {|word| "0.#{word}" }

当使用 print array 时,输出如下:

0.2.55 0.2.91 0.3.54 0.4.21 0.5.26 0.6.32.

当我到达 60 秒时,该列表会以秒为单位继续,而它应该变成分钟,例如:

0.61.54
0.63.78

我想将任何超过 60 秒的内容表示为 m.ss.hs,即

“1.1.54”
“1.3.78”

我可以用模 % 60 来做到这一点,但我不确定如何处理整个数组。我在玩弄第一个小数点(分钟)前的数字作为变量,如果 秒数 % 60 == 0,则将 1 添加到变量中,但这对 120 秒没有帮助,因为 120 % 60 == 0 也是如此。

我的代码可以运行到 60 秒,我希望它能将超过 60 秒的任何内容适本地转换为分钟。我找不到任何解释如何修改小数点后三位数组(而不是标准 h:m:s 格式)的内容。非常感谢任何和所有帮助。

最佳答案

这里是将您上面描述的格式中的秒数转换为minutes.seconds.hundredths

格式的方法
def display_minute(sec)
round_sec = sec.to_i
# Get the minute
m = round_sec / 60
# Get the remaining seconds
s = round_sec % 60
# The hundredth as integer
h = (sec - round_sec).round(2) * 100
h = h.to_i
# Combine result
[m, s, h].join('.')
end

此方法的一些结果:

display_minute(6.320953)
=> "0.6.32"
display_minute(61.320953)
=> "1.1.32"
display_minute(121.320953)
=> "2.1.32"
display_minute(185.320953)
=> "3.5.32"

关于ruby - 修改多小数点数组,秒转分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com