go學習1

來源:互聯網
上載者:User

標籤:

 1 package main 2  3 import ( 4     "bufio" 5     "fmt" 6     "math" 7     "os" 8     "runtime" 9 )10 11 const result = "Polar radius=%.02f θ=%.02f° → Cartesian x=%.02f y=%.02f\n"12 13 var prompt = "Enter a radius and an angle (in degrees), e.g., 12.5 90, " +14         "or %s to quit."15 16 type polar struct {17     radius float6418     θ      float6419 }20 21 type cartesian struct {22     x   float6423     y   float6424 }25 26 func init() {27     if runtime.GOOS == "windows" {28         prompt = fmt.Sprintf(prompt, "Ctrl+Z, Enter")29     } else { // Unix-like30         prompt = fmt.Sprintf(prompt, "Ctrl+D")31     }32 }33 34 func main() {35     questions := make(chan polar)36     defer close(questions)37     answers := createSolver(questions)38     defer close(answers)39     interact(questions, answers)40 }41 42 func createSolver(questions chan polar) chan cartesian {43     answers := make(chan cartesian)44     go func() {45         for {46             polarCoord := <-questions47             θ := polarCoord.θ * math.Pi / 180.0 // degrees to radians48             x := polarCoord.radius * math.Cos(θ)49             y := polarCoord.radius * math.Sin(θ)50             answers <- cartesian{x, y}51         }52     }()53     return answers54 }55 56 func interact(questions chan polar, answers chan cartesian) {57     reader := bufio.NewReader(os.Stdin)58     fmt.Println(prompt)59     for {60         fmt.Printf("Radius and angle: ")61         line, err := reader.ReadString(‘\n‘)62         if err != nil {63             break64         }65         var radius, θ float6466         if _, err := fmt.Sscanf(line, "%f %f", &radius, &θ); err != nil {67             fmt.Fprintln(os.Stderr, "invalid input")68             continue69         }70         questions <- polar{radius, θ}71         coord := <-answers72         fmt.Printf(result, radius, θ, coord.x, coord.y)73     }74     fmt.Println()75 }

 

go學習1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.