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).

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

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题