英文:
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 <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("%d\n", zbroj(k));
printf("%d", 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& k) {
...
}
PS. %d is for integer and you need to use %f for float.
printf("%f\n", zbroj(k));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论