将前缀表达式转换为后缀表达式。

huangapple go评论74阅读模式
英文:

Convert prefix to post

问题

我正在尝试将一些C代码转换为Go代码。

for i := l + 1; i < r; i++ {
    ans = max(ans, nums[l]*nums[i]*nums[r]+maxCoin(dp, l, i, nums)+maxCoin(dp, i, r, nums))
}

Go语言没有前缀操作符,你可以将这个循环转换为使用后缀操作符的形式吗?

英文:

I am trying to convert some C code into Go.

for i := l + 1; i &lt; r; ++i {
	ans = max(ans, nums[l]*nums[i]*nums[r]+maxCoin(dp, l, i, nums)+maxCoin(dp, i, r, nums))
}

Go doesn't have prefix operator, how can I convert this loop to use postfix?

答案1

得分: 3

使用后缀递增语句,在这种情况下没有任何区别:

for i := l + 1; i < r; i++ {
    ans = max(ans, nums[l]*nums[i]*nums[r]+maxCoin(dp, l, i, nums)+maxCoin(dp, i, r, nums))
}

只有当你使用递增/递减运算符形成的表达式的结果时,差异才会有所影响,但由于在Go中它们甚至不是运算符而是语句,所以并不重要。有关详细解释,请参见FAQ: 为什么++和--是语句而不是表达式?为什么是后缀而不是前缀?

英文:

Use a postfix increment statement, it doesn't make any difference in this case:

for i := l + 1; i &lt; r; i++ {
	ans = max(ans, nums[l]*nums[i]*nums[r]+maxCoin(dp, l, i, nums)+maxCoin(dp, i, r, nums))
}

The difference only matters when you're using the result of the expression formed by the increment / decrement operator, but since in Go they're not even operators but statements, it doesn't matter. For reasoning, see FAQ: Why are ++ and -- statements and not expressions? And why postfix, not prefix?

huangapple
  • 本文由 发表于 2017年8月28日 22:51:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/45921822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定