我在文件 mag.c 中有一个函数 mag,用于计算数组的大小。
#include <math.h>
#include "mag.h"
long double mag(long double arr[], int len){
long double magnitude=0;
for(int i=0;i<len;i++)
magnitude+=pow(arr[i],2);
magnitude=pow(magnitude,0.5);
return magnitude;
}
我希望它接受双精度和长双精度数组。我在其他地方读过(例如here https://stackoverflow.com/a/39845432/17284956)如果参数与函数声明不匹配,它将被隐式转换为正确的类型。我写了一个函数 test.c 来测试这个。
#include <math.h>
#include <stdio.h>
#include "mag.h"
int main(){
double arr1[3]={0.0,1.1,2.2};
printf("%Lf",mag(arr1,3));
return 0;
}
然而,这产生了一个错误
test.c: In function ‘main’:
test.c:7:19: warning: passing argument 1 of ‘mag’ from incompatible pointer type [-Wincompatible-pointer-types]
printf("%Lf",mag(arr1,3));
^~~~
In file included from test.c:3:
mag.h:4:29: note: expected ‘long double *’ but argument is of type ‘double *’
long double mag(long double arr[], int len);
将数组声明为 long double 可以使函数正常工作。我还尝试更改头文件中的参数类型,但返回 -nan。有没有简单的方法可以使 mag 函数同时接受 double 和 long double 参数,或者制作两个单独的函数会更简单吗? (如果我需要为双精度和长双精度参数创建单独的函数,我需要对很多文件执行此操作。)