c - 'long' 之前的预期表达式

标签 c compiler-errors c11

我是编程新手,我正在使用一本书来帮助我编写一些代码,这些代码将在用户输入“x”后求解 ln(1+x)。我的语法与书中示例中的语法完全相同,但我不断收到 error: expected expression before 'long' on line 28。第 28 行是读取 long double y 的行= 日志(1+(x));

#include <stdio.h>
#include <math.h>
#define LOG(X) _Generic((X),\
  long double: log(1+(x))\
)

int main()
{

   double x;

   printf("Please enter a number from -1 to +1: ");
   scanf("%f", &x);

   long double y = LOG(1+(x));

   printf("From C math library: ln(1+x) = %f\n", y);

}

最佳答案

首先,您的通用宏是为 long double 类型编写的。您提供了一个double 参数xlong doubledouble 是两种不同的类型。您没有为 double 定义通用分支,这意味着您的宏不会针对 double 参数进行编译。将 x 的类型更改为 long double 或使您的通用宏支持 double 参数。

此外,这是编写LOG 宏的一种非常奇怪的方式。为什么要在宏中明确使用 1 + (x) 作为 log 参数?如果明天您要计算 LOG(2 + y) 怎么办?您的宏仍然会坚持计算 log(1 + (x)),这根本没有任何意义。更明智的做法是将 X 传递给 log

#define LOG(X) _Generic((X),\
  long double: log(X)\
)

其次,为了scanf double 值,您需要%lf 格式说明符。 %f 用于float。要printf long double 值,您需要%Lf 格式。

关于c - 'long' 之前的预期表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178015/

相关文章:

可以使用多个 _Generic 来创建字符串文字吗?

c - 当宏在结构数组中时,如何将宏的名称转换为文字字符串?

c - 在C中将值插入二叉树根

python - 安装Python库时出错?

c - Visual Studio 2017 不支持C11 新特性_Generic

c - memcpy(&a + 1, &b + 1, 0) 是在 C11 中定义的吗?

c - 重复的 typedef 错误

c - struct pthread_rwlock_t 成员说明

actionscript-3 - 错误1180,闪存

c++ - 未定义对在单独文件中定义的成员函数的引用