2014年7月2日 星期三

go語言 教學2 條件式If else...switch

func main() {
 for i := 0; i < 20; i++ {
  if i%2 == 0 {
   fmt.Println("even:", i)
  } else {
   fmt.Println("odd:", i)
  }
 }
}
 
 if i%2 == 0
 
golang if 條件式省略了() 無需括號即可做條件判斷

多重條件式

func main() {
 scores := []int{30, 50, 60, 80, 70, 90}
 for i := 0; i < len(scores); i++ {
  s := scores[i]
  if s/20 == 5 {
   fmt.Printf("score: %d is S\n", s)
  } else if s/20 == 4 {
   fmt.Printf("score: %d is A\n", s)
  } else if s/20 == 3 {
   fmt.Printf("score: %d is B\n", s)
  } else if s/20 == 2 {
   fmt.Printf("score: %d is C\n", s)
  } else {
   fmt.Printf("score: %d is D\n", s)
  }
 }
}
 
對於多個條件情況下,可以在else後,再添加一個 if...else
或者改使用switch條件判斷
 
func main() {
 scores := []int{30, 50, 60, 80, 70, 90}
 for i := 0; i < len(scores); i++ {
  s := scores[i]
  switch level := s / 20; level {
  case 5:
   fmt.Printf("score: %d is S\n", s)
  case 4:
   fmt.Printf("score: %d is A\n", s)
  case 3:
   fmt.Printf("score: %d is B\n", s)
  case 2:
   fmt.Printf("score: %d is C\n", s)
  default:
   fmt.Printf("score: %d is D\n", s)
  }
 }
} 
 
case 後允許有多個條件
case 5, 3, 2:
如所有條件分不符合,則執行default:後的語句。
 
 
 
 
 
 

沒有留言:

張貼留言