Sign in to follow this  

[solved] strange error with floats or doubles

This topic is 3589 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi everyone! I have a little problem with my code. I have created a small application to display quadratic NURBS in 2D. The control points and the knot vector of the curve are defined in the following lines: float points[][] = {{/*x*/10, /*y*/10, /*weight*/1}, {410, 10, 0.5}, {410, 410, 1}}; float knotVector[] = {0, 0.2, 0.4, 0.6, 0.8, 1}; The code works perfectly, but when i replace, for example, "0.5" with "1/2" or "0.2" with "1/5" the program stops running and it doesn't display the curve. Do you have any idea of what's wrong? Thanks. [Edited by - smeyel on February 16, 2008 6:43:40 AM]

Share this post


Link to post
Share on other sites
The expression 1/2 performs an integer division. That is, the integer 1 divided by the integer 2. Because of this, the result is also an integer. Since integers cannot express decimal numbers, the result is rounded down. In this case, both 1/2 and 1/5 are rounded down to 0.

To perform a floating-point division, either cast one or both of the operands to a double, or append .0 to either (or both) number(s).

eg.
1.0/2.0, 1.0/5.0


This will correctly generate 0.2 and 0.5.

Share this post


Link to post
Share on other sites
The expression is being evaluated as integer math before being assigned to float storage. Change the integer literals to floats.

1 / 2 => 1.0 / 2.0 or 1.0f / 2.0f

Share this post


Link to post
Share on other sites

This topic is 3589 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this