Why wont this line compile?

E

E.T. Grey

double roundup(double num,double to){ return (num+to/2-((num+to/2) %
to)) ; }


Compiler error:

error C2296: '%' : illegal, left operand has type 'double'
 
S

Sebastian Wiesner

E.T. Grey said:
double roundup(double num,double to){ return (num+to/2-((num+to/2) %
to)) ; }


Compiler error:

error C2296: '%' : illegal, left operand has type 'double'

The operands of the modulo operator must be of integral type.
You can either convert the double value on the left side into an integral
type or you can use fmod function in file math.h to get the remainder of a
fdouble value.
 
A

Andrew Koenig

Maybe taking the modulus of a real number doesn't make sense?

It does, actually -- on every floating-point implementation I've ever seen,
every floating-point number represents a rational number, and modulus is
well defined on rationals. Not only that, but it is generally possible to
represent the result of modulus exactly as a floating-point number.

Nevertheless, this operation is not built into C or C++, so you need to use
the library fmod function if that's what you want.
 
G

Greg Comeau

double roundup(double num,double to){ return (num+to/2-((num+to/2) %
to)) ; }

Compiler error:

error C2296: '%' : illegal, left operand has type 'double'

Right, in C++ you can't % a double. You have to use the standard
library to do that, for instance fmod, fmodf and fmodld from math.h/cmath.
I seem to recall they will also let you catch some floating point
exceptions too, which may be why double %ing is not allowed.
BTW, I THINK C99 also has a remainder() function but not C90
so you'd need to check this, and also have a C99 compiler.
 
G

Greg Comeau

Maybe taking the modulus of a real number doesn't make sense?

I think we've been training to assume such things (certainly
elementary school does), but otherwise, I see no reason why
that needs to be the case.
 
M

Moonlit

Hi,

Oops, thank you guys, for pointing out my mistake.

Yes, now I think about it, it actually does make sense :-0

Sorry OP.

Anyway the percent operator only works with integral types

--


Regards, Ron AF Greve

http://moonlit.xs4all.nl
 
G

Greg Comeau

Oops, thank you guys, for pointing out my mistake.

Yes, now I think about it, it actually does make sense :-0

Sorry OP.

Anyway the percent operator only works with integral types

Still:
And enum's.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top