亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

即使我沒有更改任何內容,我的 go 代碼也會返回不同的結果

即使我沒有更改任何內容,我的 go 代碼也會返回不同的結果

Go
牧羊人nacy 2023-07-04 14:49:01
我正在研究將羅馬數字解碼為 10 進制數字的 kata,但我遇到了一個非常奇怪的問題。我遇到的問題是輸出不一致,我不知道為什么。我設置了以下代碼來嘗試克服挑戰(我知道它并不完美;這不是問題):package kataimport "strings"var numeralsMap = map[string]int{    "M": 1000,    "D": 500,    "C": 100,    "L": 50,    "X": 10,    "V": 5,    "I": 1,  }func Decode(roman string) int {    sum := 0    romanCpy := romanfor k := range numeralsMap { //works through romanCpy looking for matching numeralMap members    for strings.Index(romanCpy, k) != -1 {        index := strings.Index(romanCpy, k)        if index == 0 { //if it is the first one in the string, simply add it to sum and remove it from romanCpy            sum += numeralsMap[k]            if len(romanCpy) > 1 { //this is necessary to prevent an infinite loop at the last numeral                romanCpy = romanCpy[1:]             } else if len(romanCpy) <= 1 {                romanCpy = "" //removes last one at the end            }        } else if index > 0 { //if it is present but not the first one, subtract all the ones before it from sum            substr := romanCpy[:index]            for i := 0; i < len(substr); i++ {                sum -= numeralsMap[string(substr[i])]            }            if len(romanCpy) > 1 {                romanCpy = romanCpy[index:]             }        }    }}return sum}然后我有一些這樣的測試:t.Run("MDCLXVI", func(t *testing.T) {    got := Decode("MDCLXVI")    want := 1666    if got != want {        t.Errorf("got %d; want %d", got, want)    }})t.Run("IV", func(t *testing.T) {    got := Decode("IV")    want := 4    if got != want {        t.Errorf("got %d; want %d", got, want)    }})然后,當我運行測試時,有時它們會通過,有時相同的測試下次會失敗。在我的機器上以及當我嘗試在 codewars 上運行測試時都是如此。我不是在尋求幫助來解決 kata,我只是不確定為什么輸出不斷變化。任何幫助將不勝感激。提前致謝!編輯:不同的輸出確實傾向于遵循某種模式。似乎每五次就循環一次。
查看完整描述

1 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

如果后來有其他人出現,我沒有意識到 go 映射不能保證迭代順序,因此需要一個單獨的數據結構。

查看完整回答
反對 回復 2023-07-04
  • 1 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號