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'

3
  • 5
    (int)(a), not int(a) Commented Jun 29, 2014 at 7:52
  • It is also nice to put return 0; at the end. Commented Jun 29, 2014 at 7:59
  • @TheDubleM: Yes. Even nicer is to #include <stdlib.h> and use return EXIT_SUCCESS;, which is clearer than "0". Commented Jun 29, 2014 at 10:00

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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) 

1 Comment

You need to cast (a) in the comparison, otherwise it will always be true.
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?

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.