在Golang中获取平方和
发布于 2019-04-29 20:26:59
Go没有您可能在其他语言中熟悉的while、until或foreach循环结构。在Go中,for和range语句将它们全部替换:
// Three expressions, i.e. the usual
for i := 0; i < n; i++ {
}
// Single expression; same as while(condition) in other languages
for condition {
}
// No expressions; endless loop, i.e. same as while(true) or for(;;)
for {
}
// for with range; foreach and similar in other languages. Works with slices, maps, and channels.
for i, x := range []T{} {
}如果不允许使用Go的单循环结构,则只能使用递归或the goto statement
package main
import (
"fmt"
)
func main() {
var N int
fmt.Scan(&N)
fmt.Println(f(N, 0))
}
func f(n, sum int) int {
if n == 0 {
return sum
}
var Y int
fmt.Scan(&Y)
if Y > 0 {
sum += Y * Y
}
return f(n-1, sum)
}使用goto
package main
import (
"fmt"
)
func main() {
var N, Y, sum int
fmt.Scan(&N)
again:
fmt.Scan(&Y)
if Y > 0 {
sum += Y * Y
}
N--
if N > 0 {
goto again
}
fmt.Println(sum)
}https://stackoverflow.com/questions/55902279
复制相似问题