2

I have a function which is designed to round a number down to the nearest even number.

double round(double d) { floor(d + 0.5); if(d % 2 == 1) { d = d-1; } return d; } 

However, this returns the error "expression must have integral or enum type" when I try to compile the code. The error is reported from the same line as the if statement.

Can anyone point me in the right direction?

4
  • 2
    You can't use % on a double(in C++) Commented Jun 6, 2013 at 18:10
  • 6
    Also, the line floor(d + 0.5); doesn't do anything. Commented Jun 6, 2013 at 18:11
  • Adding to what @interjay said, it does do something - it returns a value, which you are silently throwing away. You need to assign the result to a variable. Commented Jun 6, 2013 at 18:16
  • What results do you want for inputs 1 (0, 2, or either?), 3 (2, 4, or either?), –1 (0, –2, either, or anything [will not be used]), and –3 (–2, –4, either, or anything?)? Commented Jun 6, 2013 at 18:28

5 Answers 5

5

The % operator is only defined for integers. You wanna use the fmod() function.

Bill is right about a proper implementation of round(double x).

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

Comments

3

The floor() function returns a double:

double floor (double x); 

which is a floating point type, not an 'integral type', like int or char. Instead of calling floor(d + 0.5); which rounds d and discards the result, you'd want something like:

int i = static_cast<int>(floor(d + 0.5)); 

2 Comments

Why is this the accepted answer? The question asks for code to round down to an even number. This neither rounds down nor rounds to an even number (when an odd number is nearer). Was the question written incorrectly?
The question asked, However, this returns the error 'expression must have integral or enum type' when I try to compile the code. The error is reported from the same line as the if statement. I was trying to explain why that particular error arose, and what could be done to fix it.
0
return floor(d/2 + 0.5) * 2; 

Of course doubles are an approximation. For 10^50 you won't get even numbers probably.

Comments

0

floor doesn't work in place, it returns the floor-ed value. Also % applies for integers so you can't re-use d. What you want is:

 int i = floor(d + 0.5); if(i % 2 == 1) { i = i-1; } return i; 

Comments

0

This version will do what you ask, returning an int.

If the parameter d is outside the range of an int, it returns 0 instead.
(maybe you want to throw an OutOfRange exception or something)

int roundDown2Even(double d) { return (INT_MIN <= d && d <= INT_MAX)? ((int)d) & ~1 : 0; } 

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.