亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go 中使用通道,我創建了一個返回地址的階乘函數

在 Go 中使用通道,我創建了一個返回地址的階乘函數

Go
梵蒂岡之花 2023-04-04 15:10:33
我正在使用 Channels 和 Go Routines 來練習偽并發。出于某種原因,我的 Factorial 函數似乎返回一個地址,而不是實際的整數值。這是我的代碼:package mainimport (    "fmt")func main() {    c := make(chan uint64)    go factorialViaChannel(8, c)    f := c //Assign go channel value to f    fmt.Println("The Factorial of 8 is", f)    myNums := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9}    product := make(chan int64)    go multiply(myNums, product) //create go routine pseudo thread    result := <-product    fmt.Println("The Result of this array multipled computation is", result)}func factorialViaChannel(value int, factorial chan uint64) {    var computation uint64    if value < 0 {        fmt.Println("Value can not be less than 0")    } else {        for i := 1; i <= value; i++ {            computation *= uint64(i)        }    }    factorial <- computation}func multiply(nums []int64, product chan int64) { //multiply numerous values then send them to a channel    var result int64 = 1    for _, val := range nums {        result *= val    }    product <- result //send result to product}這是我的結果:$ go run MultipleConcurrency.goThe Factorial of 8 is 0xc42000c028The Result of this array multipled computation is 362880為什么打印內存地址而不是值?我有點困惑。謝謝!
查看完整描述

2 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

替換這一行:

f := c //Assign go channel value to f

f := <-c //Assign go channel value to f

并初始化變量 -computation1factorialViaChannel()

像這樣:

var computation uint64 = 1


查看完整回答
反對 回復 2023-04-04
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

我想通了,問題已在下面更正:


package main


import (

    "fmt"

)


func main() {

    factorial := make(chan uint64)

    go factorialViaChannel(8, factorial)

    f := <-factorial //Assign go channel value to f

    fmt.Println("The Factorial of 8 is", f)


    myNums := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9}

    product := make(chan int64)

    go multiply(myNums, product) //create go routine pseudo thread

    result := <-product

    fmt.Println("The Result of this array multipled computation is", result)


}


func factorialViaChannel(value int, factorial chan uint64) {


    var computation uint64 = 1


    if value < 0 {

        fmt.Println("Value can not be less than 0")


    } else {

        for i := 1; i <= value; i++ {

            computation *= uint64(i)


        }


    }

    factorial <- computation


}


func multiply(nums []int64, product chan int64) { //multiply numerous values then send them to a channel

    var result int64 = 1

    for _, val := range nums {

        result *= val

    }

    product <- result //send result to product

}


查看完整回答
反對 回復 2023-04-04
  • 2 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號