#include <stdio.h>
#define mean(x,N) ( double _sum=0.0; for (int _i=0;_i<N;++_i) _sum+=x[_i]; _sum/N )
int main() {
const int N=100;
int i[N]; double d[N];
// here we fill the arrays with data, and then
printf("%f %f %f\n", mean(i,N), mean(d,N));
}
如何在纯C中适当地定义宏,或者在不编码两个函数的情况下以另一种方式完成此操作?
答案 0 :(得分:1)
在这种情况下,宏不起作用。
函数的参数必须是表达式。你上面所拥有的不是表达而是一系列陈述。你不能通过循环来解决这个问题。
只需定义功能,一个接受double *
和int
,另一个接受int *
和int
,以执行此操作。不要使用函数可以执行的宏。
答案 1 :(得分:1)
没有可移植的方法来编写宏来从语句中返回值,尤其是复杂的语句。您希望使用宏来实现多态事物......您可以使用C ++重载函数来实现此目的。
对于C,您可以编写一个更新变量并将该变量传递给printf
的宏。请注意,宏是非常重要的错误来源。
您也可以使用C11通用功能,但通常缺少对这些功能的支持。
这是一次尝试:
#include <stdio.h>
#define set_mean(res,x,N) do { res = 0; for (int i_ = 0; i_ < (N); i_++) res += (x)[i_]; res /= (N); } while (0)
int main(void) {
const int N = 100;
int i[N];
double d[N];
double ires, dres;
// here we fill the arrays with data, and then
set_mean(ires, i, N);
set_mean(dres, d, N);
printf("%f %f %f\n", ires, dres);
}