我想作为函数参数传递一个struct变量(对不起,英语不好)。以下是我想做的事:
#include <stdio.h>
#include <stdint.h>
typedef struct {
int temp;
int hum;
int oxy;
} Data;
Data sens1;
Data sens2;
Data sens3;
sens1.temp = 5;
sens2.temp = 10;
sens3.temp = 15;
int ort(Data temp1 , Data temp2 , Data temp3)
{
int ort = ((temp1 + temp2 + temp3) / 3);
return ort;
}
int main(void)
{
printf("%d", ort(sens1.temp, sens2.temp, sens3.temp));
return 0;
}如何将名为temp的struct成员添加到函数ort()作为参数?
发布于 2022-08-06 09:34:42
您不能添加结构,这就是您在temp1 + temp2 + temp3中要做的。
你可能想要这个:
int ort(Data sensor1 , Data sensor2, Data sensor2)
{
int ort = ((sensor1.temp + sensor2.temp + sensor2.temp) / 3);
return ort;
}
...
printf("%d" , ort(sens1, sens2, sens3);
...或者这个:
int ort(int temp1, int temp2, int temp3)
{
int ort = ((temp1 + temp2 + temp3) / 3);
return ort;
}
...
printf("%d" , ort(sens1.temp, sens2.temp, sens3.temp);
...发布于 2022-08-06 13:40:00
如果希望传递对结构的引用,而不是传递整个结构,典型的方法如下:
#include <stdio.h>
#include <stdint.h>
struct data {
int temp;
int hum;
int oxy;
};
struct data sens1 = { .temp = 5 };
struct data sens2 = { .temp = 10 };
struct data sens3 = { .temp = 15 };
float
ort(const struct data *d1, const struct data *d2, const struct data *d3)
{
return (float)(d1->temp + d2->temp + d3->temp) / 3;
}
int
main(void)
{
printf("%f\n", ort(&sens1, &sens2, &sens3));
return 0;
}https://stackoverflow.com/questions/73258614
复制相似问题