I passed a struct to a function and called the variables inside a function from struct but it still returns 0

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

I passed a struct to a function and called the variables inside a function from struct but it still returns 0

问题

我试图将这些数字相加,但它打印出0。

#include <stdio.h>
#include <stdlib.h>

struct kmplx{
    float real;
    float im;
};

float zbroj(struct kmplx k){
    k.real = 5;
    k.im = 1;
    float zbr = k.real + k.im;
    return zbr;
}
float umn(struct kmplx k){
    float prod = k.real * k.im;
    return prod;
}

int main(){
    struct kmplx k;
    printf("%f\n", zbroj(k));
    printf("%f", umn(k));
}
英文:

I am trying to add up the numbers but it prints out 0.

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

struct kmplx{
    float real;
    float im;
};

float zbroj(struct kmplx k){
    k.real = 5;
    k.im = 1;
    float zbr = k.real + k.im;
    return zbr;
}
float umn(struct kmplx k){
    float prod = k.real * k.im;
    return prod;
}

int main(){
    struct kmplx k;
    printf(&quot;%d\n&quot;, zbroj(k));
    printf(&quot;%d&quot;, umn(k));
}

I tried to call the variables from struct in main but same result happens.

答案1

得分: 0

当我们将一个结构体传递给函数时,它会传递一个副本。因此,在大多数情况下,我们使用指针或引用来传递。
而且正因为如此,在zbroj(k)运行之后,主函数中的变量k仍然与之前相同,因为你已经写入了它的副本的数据。
因此,umn(k)返回0(在某些情况下,可能会是一个意外的数字)。

在你的情况下,你需要将函数定义如下。

float zbroj(struct kmplx& k) {
...
}

PS. %d 用于整数,你需要使用 %f 用于浮点数。

printf("%f\n", zbroj(k));
英文:

When we pass a struct to a function, it'll pass a copy of it. So most of the cases, we pass using a pointer or reference.
And because of it, after zbroj(k) runs, k variable in the main function is still the same as before because you have written data to copy of it.
As a result, umn(k) returns 0 (in some cases, it could be an unexpected number).

In your case, you need to define function as following.

float zbroj(struct kmplx&amp; k) {
...
}

PS. %d is for integer and you need to use %f for float.

printf(&quot;%f\n&quot;, zbroj(k));

huangapple
  • 本文由 发表于 2023年5月11日 02:45:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221695.html
匿名

发表评论

匿名网友

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

确定