为了账号安全,请及时绑定邮箱和手机立即绑定

在 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 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信