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 求会做聚类,TCN的朋友有偿线上指导。以下是目前遇到的问题
  • ¥100 无网格伽辽金方法研究裂纹扩展的程序
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活