Golang尝试存储指针的值

huangapple go评论84阅读模式
英文:

Golang trying to store the values of pointers

问题

我有一个问题,对于如何解决它感到困惑。

我有这个任务:

1. 将除法的结果存储在指针 a 指向的 int 
2. 将除法的余数存储在指针 b 指向的 int 

我的代码是:

package main

import "fmt"

func Function(a *int, b *int) {
	*a = *a / *b
	*b = *a % *b
}

func main() {
	a := 13
	b := 2
	Function(&a, &b)
	fmt.Println(a)
	fmt.Println(b)
}

输出应该是 6 和 1,然而,我不知道如何在 Function 函数中编写代码,以正确地存储结果。我该如何修复我的代码?Function 函数应该将 a 的解引用值除以 b 的解引用值。

英文:

I have a problem and I'm confused about how to solve it.

I have this task:

1. Store the result of the division in the int which a points to.
2. Store the remainder of the division in the int which b points to.

My code is:

package main

import "fmt"

func Function(a *int, b *int) {
	*a = *a / *b
	*b = *a % *b
}

func main() {
	a := 13
	b := 2
	Function(&a, &b)
	fmt.Println(a)
	fmt.Println(b)
}

The output should be 6 and 1, however, I don't know how to write the code in the Function func the way it would store the results properly. How do I fix my code? Function should divide the dereferenced value of a by the dereferenced value of b.

答案1

得分: 1

该函数在第二个语句中使用*a的值之前会破坏它。使用以下代码:

func Function(a *int, b *int) {
    *a, *b = *a / *b, *a % *b
}

=的右侧表达式在赋值给左侧变量之前进行求值。

另一个选项是将*a / *b赋值给一个临时变量:

func Function(a *int, b *int) {
    t := *a / *b
    *b = *a % *b
    *a = t
}
英文:

The function clobbers the value of *a before the value is used in the second statement. Use this code:

func Function(a *int, b *int) {
	*a, *b = *a / *b, *a % *b
}

The expressions on the right hand side of the = are evaluated before assignments to the variables on the left hand side.

Another option is to assign *a / *b to a temporary value:

func Function(a *int, b *int) {
	t := *a / *b
	*b = *a % *b
	*a = t
}

huangapple
  • 本文由 发表于 2022年8月5日 12:28:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/73244676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定