gpt4 book ai didi

c - 从 C 中的函数返回多个值

转载 作者:太空狗 更新时间:2023-10-29 16:11:09 25 4
gpt4 key购买 nike

int getPositionsH(int r, int ans, int size){
int x=0;
int y=0;
if (ans==9){
x =0;
} else
x=(rand()%size);

y=(rand()%10);
return x;
return y;
}

基本上这是一个 c 中的函数,应该返回 2随机生成的位置 x 和 y。但是在调试时我注意到执行此操作后 x 和 y 仍然为空。不知道为什么因为我写了返回和一切。任何想法为什么?任何帮助是赞赏。

最佳答案

在 C 语言中,一个函数只能返回一个值。实际上,该函数仅返回 x 而语句 return y; 没有任何效果——它是无法访问的代码.

如果你想返回多个值,你可以传递指针并在它们的内容中返回值,或者创建一个结构并返回值。

typedef struct position {
int x;
int y;
}pos_type;

pos_type getPositionsH(int r, int ans, int size){
pos_type p;
int x=0;
int y=0;
if (ans==9){
x =0;
} else
x=(rand()%size);

y=(rand()%10);

p.x = x;
p.y = y;
reutrn p;
}

在调用者中:

pos_type t = getPositionsH(...);

int x = t.x;
int y = t.y;
.....

关于c - 从 C 中的函数返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34240267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com