Ceil function like php?

I want to return the smallest integer value greater than or equal to integer division. So I used math.ceil , but cannot get the value I want.

 package main import ( "fmt" "math" ) func main() { var pagesize int = 10 var length int = 43 d := float64(length / pagesize) page := int(math.Ceil(d)) fmt.Println(page) // output 4 not 5 } 

http://golang.org/pkg/math/#Ceil

http://play.golang.org/p/asHta1HkO_

What's wrong? Thanks.

+14
source share
4 answers

Line

 d := float64(length / pagesize) 

Converts to swim result of division. Since the partition itself is a whole division, it leads to 4, so d = 4.0 and math.Ceil(d) is 4.

Replace the string with

 d := float64(length) / float64(pagesize) 

and you will have d=4.3 and int(math.Ceil(d))=5 .

+35
source

Convert sheet length and size to floats before dividing:

 d := float64(length) / float64(pagesize) 

http://play.golang.org/p/FKWeIj7of5

+9
source

Please note that you can use

 x, y := length, pagesize q := (x + y - 1) / y; 

for x >= 0 and y > 0 . It will also be very fast.

Or to avoid overflow x+y :

 q := 1 + (x - 1) / y 

The same as the version of C ++: Quick ceiling of integer division in C / C ++

+4
source

You can check the remainder to see if it should be increased to the next integer.

 page := length / pagesize if length % pagesize > 0 { page++ } 
0
source

Source: https://habr.com/ru/post/957772/


All Articles