if语句看起来就像C或Java。但是它没有小括号(),而大括号{}是必须有的。
这听起来是不是有点熟悉?
1 package main
2
3 import (
4 "fmt"
5 "math"
6 )
7
8 func sqrt(x float64) string {
9 if x < 0 {
10 return sqrt(-x) + "i"
11 }
12 return fmt.Sprint(math.Sqrt(x))
13 }
14
15 func main() {
16 fmt.Println(sqrt(2), sqrt(-4))
17 }
1.4142135623730951 2i
注:
math.Sqrt(x)是开平方函数
像For语句一样,IF语句可以在条件语句前加一个语句。在这条语句声明的变量使用范围仅仅到if语句结束。
(试着把return返回v)
1 package main
2
3 import (
4 "fmt"
5 "math"
6 )
7
8 func pow(x, n, lim float64) float64 {
9 if v := math.Pow(x, n); v < lim {
10 return v
11 }
12 return lim
13 }
14
15 func main() {
16 fmt.Println(
17 pow(3, 2, 10),
18 pow(3, 3, 20),
19 )
20 }
9 20
注:
math.Pow(x, n)是求X的N的平方。
在if条件语句前语句声明的变量可以在任何一个else语句内使用。
1 package main
2
3 import (
4 "fmt"
5 "math"
6 )
7
8 func pow(x, n, lim float64) float64 {
9 if v := math.Pow(x, n); v < lim {
10 return v
11 } else {
12 fmt.Printf("%g >= %g\n", v, lim)
13 }
14 // can't use v here, though
15 return lim
16 }
17
18 func main() {
19 fmt.Println(
20 pow(3, 2, 10),
21 pow(3, 3, 20),
22 )
23 }
27 >= 20 9 20

被折叠的 条评论
为什么被折叠?



