>
> On Sun, Aug 2, 2020 at 2:09 PM Martin Møller Skarbiniks Pedersen <
> traxp...@gmail.com <javascript:>> wrote:
>
>> I have written my first little piece of Go-code.
>> However it took some time and code for me to divide a int64 by 4 and 
>> round down. 
>>
>> How can the last two lines be rewritten?
>>
>> Regards
>> Martin
>>
>> package main
>>
>> import (
>> "fmt"
>> "bufio"
>> "math"
>> )
>>
>>
>> var cash int64
>> scanner := bufio.NewScanner(os.Stdin)
>>
>> scanner.Scan()
>> cash,err = strconv.ParseInt(scanner.Text(), 10, 64)
>> if err != nil {
>> fmt.Println(err)
>> }
>>
>> var bet int64
>> bet = int64(math.Ceil(float64(cash)/float64(4)))
>> cash = cash - bet
>>
>> On Sunday, 2 August 2020 23:25:23 UTC+2, Kurtis Rader wrote:
>>>
>>> In addition to Jake's question regarding whether you want to round up or 
>>> down I'll point out there isn't any to cast to float64 and back to int64. 
>>> If you want to "round down" just divide by four. If you want to "round up" 
>>> add one less than the divisor before dividing; e.g., bet := (cash + 3) / 
>>> 4. Notice the ":=" which avoids the need for the "var bet int64" statement.
>>>
>>
Oops. I actually needed to round up so I think I still need the math.Ceil() 
function.

If I write like this:

<code>
import (
"fmt"
"bufio"
"math"
)

var cash int64
scanner := bufio.NewScanner(os.Stdin)

scanner.Scan()
cash,err = strconv.ParseInt(scanner.Text(), 10, 64)
if err != nil {
fmt.Println(err)
}

bet := math.Ceil(cash/4)
</code>
then the compiler complains:
./casino.go:36:24: cannot use cash / 4 (type int64) as type float64 in 
argument to math.Ceil

My only solution is a lot of type-casting:
bet := int64(math.Ceil(float64(cash)/float64(4)))

Is there a better way to divide by 4 and round up to nearest integer?

ps. The full code can be found at: https://pastebin.com/1j7NJF0k


Regards
Martin



-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/e1064f2e-1120-444f-a9d9-bb7881969e49o%40googlegroups.com.

Reply via email to