0

This is the program:

#include <stdio.h>
#define round(a) ((a-0.5)<int(a))?int(a):int(a+1)
int main() {
double a = 5.2;
int m = round(a);
printf("%d", m); }

and it shows the error: expected expression before 'int'

user3787309
  • 109
  • 1
  • 1
  • 4

4 Answers4

2

round is a name reserved by the standard C library so it is undefined behaviour to call your macro that name (even if you don't include math.h).

Your algorithm could be better expressed like this:

#define my_round(a)  ( (int)((a) + 0.5) )

which also has the benefit of only evaluating its argument once.

It would be preferable to use an inline function:

inline int my_round(double d)
{
    return d + 0.5;    
}

Note that both options cause undefined behaviour if a is outside the bounds of INT_MIN, INT_MAX roughly . If it's in a critical environment you should make your inline function check the bounds of d before doing the conversion to int.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • 1
    The original macro in the question produces the wrong result (for the specification implicit in the name “round”) for even floating-point numbers between 2^52 and 2^53. Your version produces the wrong result for odd floating-point numbers between 2^52 and 2^53, and also for the predecessor of 0.5. – Pascal Cuoq Jun 29 '14 at 08:07
0

The error is because of int(a). Syntactically it is wrong. It should be (int)(a).

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
0

This

#define round(a) ((a-0.5)<int(a))?int(a):int(a+1)

Has the brackets in the wron places

Should be

#define round(a) (((int)((a)-0.5))<(a))?(int)(a):(int)(a+1)
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

The problem is that int(a) is not valid C.

Redefine your macro as follows:

#define round(a) (((a)-0.5)<(int)(a))?(int)(a):(int)(a+1)

Note that I've also added parentheses around a in (a)-0.5.

P.S. What's the reason for making it a macro and not, say, a function?

NPE
  • 486,780
  • 108
  • 951
  • 1,012