dongyu8694 2019-04-27 13:02
浏览 831

* float32和int值相乘

I have 2 fields that I have to multiply. One is a *float32 field and another is an int field. How can I multiply these fields?

var totalPrice *float32
var price *float32
var volume int

this code doesn't work. I get the error ... mismatched types *float32 ...

totalPrice = price * volume

  • 写回答

1条回答 默认 最新

  • dot_0620 2019-04-27 18:20
    关注

    You need to convert using type conversion as is explained quickly here. In this case as mkopriva highlight in his comment, you should convert volume variable's value to a float32.

    Also allow to show a way to deal with nil values that has a meaning in the application level, for that i wrote the float32PtrToFloat(*float32,float32) with the second parameter that allows you to specify what value shall be taken instead of nil.

    Assuming that a nil value translates to zero value, here goes the complete example

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var totalPrice *float32
        var price *float32
        var volume int
    
        var total = float32PtrToFloat(price, 0) * float32(volume)
        totalPrice = &total
        fmt.Println(*totalPrice)
    
    }
    
    func float32PtrToFloat(price *float32, valueIfNil float32) float32 {
        if price == nil {
            return valueIfNil
        } else {
            return *price
        }
    }
    

    And a personal reading, following JimB advice, try to not use floats for currency values as floating point arithmetic is not reliable. Instead use integer values, using the 1 as the lower value in the current currency, for example:

    • 1 = 1 penny (or)
    • 1 = 1 cent (or)
    • 1 = 1 centavo (in my case)
    评论

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?