簡體   English   中英

int16數字加上golang中的float64

[英]int16 number plus float64 in golang

我想做一件簡單的事情:

func (this *ScoreProvider) getScore()(res float64) {
    var score1 int16 = 500
    var score2 int16 = 400
    var score3 int16 = 300
    var score4 int16 = 200
    res = score1 * 0.25 + score2 * 0.25 + score3 * 0.25 + score4 * 0.25

    return
}

但這報告一個錯誤:

can not use score1 * 0 + score2 * 0 + score3 * 0 + score4 * 0 (type int16) as type float64 in assignment

我該怎么做呢?

Go不提供隱式數字轉換,請參閱以下常見問題解答: 為什么Go不提供隱式數字轉換?

這意味着您在進行算術運算時不能混合使用不同的類型。 它們必須是同一類型。 規格

除非操作涉及移位或未類型化的常數,否則操作數類型必須相同

您的情況有所不同,因為0.25是未類型化的常量,但是由於它具有小數部分,因此無法將其轉換/解釋為int16因此會遇到編譯時錯誤。 規格

如果常量值不能表示為相應類型的值,則會出錯。

在這種情況下,您有3個選擇:

  1. 將分數顯式轉換為float64

     res = float64(score1) * 0.25 + float64(score2) * 0.25 + float64(score3) * 0.25 + float64(score4) * 0.25 
  2. 對您的score變量使用float64類型。

     var score1 float64 = 500 var score2 float64 = 400 // ... 
  3. 由於您的算法會計算平均值,因此您可以執行以下操作:

     res = float64(score1 + score2 + score3 + score4) / 4 

您的常數(0.25)被截斷為整數(0)。

兩種解決方法:

將score1等變量轉換為float32:

var score1 int16 = 500
var score2 int16 = 400
var score3 int16 = 300
var score4 int16 = 200
res := float32(score1)*0.25 + float32(score2)*0.25 + float32(score3)*0.25 + float32(score4)*0.25

fmt.Println("Score", res)

或更明智的選擇,而不是將它們聲明為int16,而是將它們聲明為float32:

var score1a float32 = 500
var score2a float32 = 400
var score3a float32 = 300
var score4a float32 = 200
res2 := score1a * 0.25 + score2a * 0.25 + score3a * 0.25 + score4a * 0.25

fmt.Println("Result 1", res)
fmt.Println("Result 2", res2)

隨時隨地的游樂場

go中沒有自動類型提升功能,您需要包含顯式轉換。

我會像這樣編寫您的代碼:

package main

import "fmt"

func getScore() float64 {
    s1, s2, s3, s4 := int16(500), int16(400), int16(300), int16(200)
    return (float64(s1) + float64(s2) + float64(s3) + float64(s4)) * 0.25
}

func main() {
    fmt.Println(getScore())
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM