c 函数是否可以同时接受 double 和 long double 参数?

2023-12-20

我在文件 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 参数,或者制作两个单独的函数会更简单吗? (如果我需要为双精度和长双精度参数创建单独的函数,我需要对很多文件执行此操作。)


...它将隐式转换为正确的类型。我写了一个函数 test.c 来测试这个。

这适用于某些参数,例如double转换成long double, 但不是double *转换成long double *.

C has _Generic只是为了这种编程。使用mag(arr, len) _Generic((arr) ...指导代码的选择。

我建议也使用long double功能和long double常数与long double对象。

long double mag_long_double(const long double arr[], int len) {
  long double magnitude = 0;
  for (int i = 0; i < len; i++)
    magnitude += powl(arr[i], 2);  // powl
  magnitude = sqrtl(magnitude);
  return magnitude;
}

double mag_double(const double arr[], int len) {
  double magnitude = 0;
  for (int i = 0; i < len; i++)
    magnitude += pow(arr[i], 2);
  magnitude = sqrt(magnitude);
  return magnitude;
}

#define mag(arr, len) _Generic((arr), \
  long double *: mag_long_double, \
  double *: mag_double \
  )((arr), (len))

int main(void) {
  double arr1[3] = {0.0, 1.1, 2.2};
  printf("%f\n",mag(arr1,3));
  long double arr2[3] = {0.0, 3.3L, 4.4L}; // Add 'L'
  printf("%Lf\n",mag(arr2,3));
  return 0;
}

Output

2.459675
5.500000
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c 函数是否可以同时接受 double 和 long double 参数? 的相关文章