英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论