dongliao4353 2018-12-17 18:37
浏览 24
已采纳

将具有内部条件的循环从python转换为golang

im converting some code from python to go

here i want write equal code in go lang:

python :

while g_day_no >= g_days_in_month[i] + (i == 1 and leap):
    g_day_no -= g_days_in_month[i] + (i == 1 and leap)
    i+=1

my try:

leap := int32(1)
var i = int32(0)
for g_day_no >= (g_days_in_month[i] + (i == 1 && leap)){
    g_day_no -= g_days_in_month[i] + (i == 1 && leap)
    i+=1
}

but i have error in ide that say :

Invalid operation: i == 1 && leap (mismatched types bool and int32)

for this section (i == 1 && leap)

how can i correct this part of my code?

  • 写回答

1条回答 默认 最新

  • duanhe3393 2018-12-17 18:42
    关注

    Go is more strict about conditions. It requires booleans. leap is an integer, so just check the value:

    g_day_no >= (g_days_in_month[i] || (i == 1 && leap!=0))

    More detailed answer

    Booleans (True and False) in Python correspond to the following integer values:

    True=>1 False=>0

    This can be seen with the following:

    >>> True+0
    1
    >>> False+0
    0
    

    Therefore, when you have two booleans that are being added together, its the same as an OR:

    True  + True  => 2 (True)
    False + True  => 1 (True)
    True  + False => 1 (True)
    False + False => 0 (False)
    

    This is the same "truth table" as OR:

    True OR True => True False OR TRUE => True True OR False => True FALSE OR FALSE => False

    Therefore, change your + to an || (|| is OR in Go).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料