Reputation: 19
I'm VERY new to programming, and I'm using a book to help me write some code that will solve ln(1+x) after the user inputs "x". My syntax is exactly the way the book has it in its example but I keep getting an error: expected expression before 'long'
on line 28. Line 28 is the line that reads long double y = LOG(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);
}
Upvotes: 0
Views: 3588
Reputation: 34585
If you are new to programming, and trying to make an example work, I would not use macros at this stage but focus on the function and the data type. Start with a double
which is the typical working type of the library interfaced by math.h
. My example shows how to calculate the natural ln with the log()
function.
As others have commented, scanf()
needs a format specifier of %lf
for a double
, however printf()
only needs the format specifier of %f
for a double
. Note that I have tested the return value from scanf()
function as well as the number you input, to check that the input was well behaved.
Lastly, you invite numbers in the range -1 <= x <= 1
yet ln(0)
is undefined, hence I have restricted the input range to exclude -1
.
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0, y;
printf("Please enter a number from -1 to +1: ");
if (1 != scanf("%lf", &x) || x <= -1 || x > 1) {
printf("I need -1 < number <= +1\n");
return 1;
}
y = log(x + 1);
printf("From C math library: ln(1+x) = %f\n", y);
return 0;
}
Here are some sample outputs:
Please enter a number from -1 to +1: -1
I need -1 < number <= +1
Please enter a number from -1 to +1: 0
From C math library: ln(1+x) = 0.000000
Please enter a number from -1 to +1: 1
From C math library: ln(1+x) = 0.693147
Upvotes: 3
Reputation: 320661
Firstly, your generic macro is written for long double
type. You supplied a double
argument x
. long double
and double
are two different types. You did not define a generic branch for double
, which means that your macro will not compile for a double
argument. Either change the type of x
to long double
or make your generic macro support double
arguments.
Also, this is a very strange way to write a LOG
macro. Why are you explicitly using 1 + (x)
as log
argument inside the macro? What if tomorrow you'll want to calculate LOG(2 + y)
? Your macro will still insist on calculating log(1 + (x))
instead, which does not make any sense at all. A more sensible thing to do would be to just pass X
to log
#define LOG(X) _Generic((X),\
long double: log(X)\
)
Secondly, in order to scanf
a double
value you need %lf
format specifier. %f
is for float
. To printf
a long double
value you need %Lf
format.
Upvotes: 4