, 어떻게 수행 할 수 per_page = 100
및 records = 1050
다음이 모아 곳소수점 이하 자릿수로 나누고 올림 할 변수를 어떻게 설정할 수 있습니까? 루비에서
number_total = records/per_page
그래서 소수가 없다? 그러면 10.5 대신 11이됩니다.
, 어떻게 수행 할 수 per_page = 100
및 records = 1050
다음이 모아 곳소수점 이하 자릿수로 나누고 올림 할 변수를 어떻게 설정할 수 있습니까? 루비에서
number_total = records/per_page
그래서 소수가 없다? 그러면 10.5 대신 11이됩니다.
편집 주석에게 다음
number_total = (records/per_page.to_f).ceil
여기에 오는 모든 악의 뿌리하십시오 조기에 최적화 방법
이class Integer
# returns quotient's ceiling integer
def div_ceil(divisor)
q = self/divisor
if self % divisor > 0
return q + 1
else
return q
end
end
end
다음 벤치 마크 코드 :
require 'benchmark'
$a = 1050
$b = 100
def float_op
($a/$b.to_f).ceil
end
def integer_op
q = $a/$b
if $a % $b > 0
return q + 1
else
return q
end
end
n = 1000000
Benchmark.bm do |x|
x.report { n.times do; float_op; end }
x.report { n.times do; integer_op; end }
end
나를 준다 이 결과
user system total real
0.160000 0.000000 0.160000 ( 0.157589)
0.130000 0.000000 0.130000 ( 0.133821)
@ lulala 악마의 또 다른 뿌리 : 체리 따기 결과.
벤치 마크를 여러 번 실행하십시오. 나는 다음과 같은 얻을 : 넥타이입니다
user system total real
0.120000 0.000000 0.120000 ( 0.119281)
0.120000 0.000000 0.120000 ( 0.123431)
.
user system total real
0.110000 0.000000 0.110000 ( 0.118602)
0.130000 0.000000 0.130000 ( 0.127195)
이는 float_op
이 더 빠름을 암시합니다.
user system total real
0.150000 0.000000 0.150000 ( 0.151104)
0.120000 0.000000 0.120000 ( 0.123836)
이는 integer_op
이 더 빠릅니다.
ceil 또는 round? 누구 한테 옳은가? thxs – AnApprentice
'1.1'에 대해 당신은 무엇을 원합니 까? 그것은 그것에 달려 있습니다. '1' 또는'2'? – sawa
들어 1.1 2 싶어요 – AnApprentice