1. 程式人生 > >go_條件和循環

go_條件和循環

錯誤 sprint 初始 fun ews 需要 () class new

package main

import (
"io/ioutil"
"fmt"
)

func grade(score int) string{
g:=""
switch {//可以省略掉switch中的判斷
case score<0 || score>100:
panic(fmt.Sprintf(
"Wrong score:%d",score))
case score <60:
g="f"
case score <80:
g="C"
case score <90:
g="B"
case score <=100:
g="A"
}
return g
}

func eval(a,b int, op string) int{
var result int
switch op{
case "+":
result = a+b
case "-":
result = a-b
case "*":
result = a*b
case "/":
result = a/b
default:
panic("unsupported operator:"+ op)
}
return result
}

func main() {
const filename = "abc.txt"
//contents,err:= ioutil.ReadFile(filename)
//if err !=nil {
// fmt.Println(err)
//}else {
// fmt.Printf("%s\n",contents)
//}
//簡便寫法,if的條件裏可以賦值,條件裏賦值的變量作用域就在這個if語句裏
if contents,err:= ioutil.ReadFile(filename);err !=nil{
fmt.Println(err)
}else {
fmt.Printf("%s\n",contents)
}

fmt.Printf("%s\n",grade(99))
fmt.Println(eval(1,2,"*"))
}

  以上是條件語句

  if條件裏可以定義變量

  switch不需要break,也可以直接switch多個條件

package main

import (
	"fmt"
	"strconv"
	"os"
	"bufio"
)

func convertToBin(n int) string{
	result :=""
	for ;n > 0 ; n /= 2 {
		lsb:=n % 2
		result = strconv.Itoa(lsb) + result
	}
	return result
}

func printFile(filename string){
	file,err := os.Open(filename)
	if err !=nil{
		panic(err)
	}
	scanner := bufio.NewScanner(file)
	for  scanner.Scan() {
		fmt.Println(scanner.Text())
	}
}

func main() {
	fmt.Println(
		convertToBin(5),
		convertToBin(128),
	)
	printFile("abc.txt")
}

  以上是循環語法

  for的條件裏不需要括號,可以省略初始條件,結束條件,遞增表達式(亦可以全部省略,為死循環)

  panic()當程序報錯時,會停掉程序,打印出錯誤

go_條件和循環