Sponsored By

Sign in to follow this  
iccaros

Better Way To Do This In C++ Convert A Double To Int

Recommended Posts

ok I am still working on my statistics program,

I have it working (I think)

but I get a compiler warning.. I believe its because this is a C way of doing this..

I have slot defined as a double for the math but need to retrun a int for the place in the array (as there is no place 0.456)

here is how I converted double slot to an int.

return slot = (int) slot;

better option for c++?

Thanks

Share this post


Link to post
Share on other sites

The warning is probably because slot is a double and function is declared as returning an int. You're casting the value of slot [edit: another weird typo, I need to run some tests] to int and then assigning it back to a double which is then implicitly converted by the compiler to int. g++ generates warnings when it does implicit conversion. The warning doesn't necessarily mean there's anything wrong: fp to integral conversion is well-defined iff the integeral type can exactly represent the whole part of the fp value. You're (probably) going to get the same result with or without the cast so you can ignore the warning if you like.

Anyway C-style casts are perfectly valid, so

return (int)slot;

will work. The idiomatic C++ would be

return static_cast<int>(slot);

but there are a lot of people who wouldn't bother with the C++-style cast in this case.

Edited by jcl

Share this post


Link to post
Share on other sites

Thanks..

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this