-2
    #include <stdio.h>
    #define f(n) (2-(1/n))
    
    int main() {
        
 printf("when n =2, %.2f\n", f(2));
         return 0;
}

Answer is 0.00.Why the output isn't 1.50

timrau
  • 22,578
  • 4
  • 51
  • 64
  • 3
    Try `#define f(n) (2-(1./(n)))` -- note the period and the extra parenthesis around `n`. BTW: most people would use uppercase letters for macro identifiers, `F(n)` in your case. – pmg Sep 28 '22 at 09:19
  • 5
    You also have undefined behaviour, because you have passed an `int` for format `%f` – Weather Vane Sep 28 '22 at 09:20
  • As it is a macro n is not necessarily an integer, it is what we send to it. – CGi03 Sep 28 '22 at 09:30
  • 1
    What everyone is failing to explain here is that everything in C has a type, including constants like `1` (int)` or `1.0` (double). If you want floating point arithmetic, you should ensure that _every single operand_ in the expression is of a floating point type. Do _not_ mix fixed point `int` with floating point `double` in the same expression, nothing good will come out of it, ever. Thus the correct answer is: `#define f(n) (2.0-(1.0/(n)))` or better yet `#define f(n) _Generic((n), double: (2.0-(1.0/(n)))` or better yet `double func (double arg)`. – Lundin Sep 28 '22 at 09:31
  • There are two problems here. One is that integer division truncates, as explained in the answer and the other comments. But the other, at least as big problem is that function-like macros are tricky, and not generally recommended any more. They have some subtle failure modes, and their use can make it much harder to see what's going on, and that's certainly the case here. I would encourage you do drop the `#define`, and either move `f`'s code inline to `main`, or write a true function `f() { … }`. – Steve Summit Sep 28 '22 at 19:01

1 Answers1

1

Since f(n) is a macro. You must write the argument as a float or a double.

#include <stdio.h>
#define f(n) (2-(1/(n)))

int main()
{
    printf("when n =2, %.2f\n", f(2.0));

    return 0;
}

Or make the macro work with floats or doubles.

#include <stdio.h>
#define f(n) (2.0-(1.0/(n)))

int main()
{
    printf("when n =2, %.2f\n", f(2));

    return 0;
}
CGi03
  • 452
  • 1
  • 3
  • 8