Floating point/integer arithmetic

Hi people.

I wonder if anyone can sort this silly problem out for me. I'm new to C++, having mostly programmed in BASIC.

Have a look at the following code:

///////////////// Code start
int i=x1;
while (i!=x2)
{
int t = i-x1;

float m = t * (0.25);
//float m = (t * (1/4));

float n = m + y1;

int j = (integer (n));
DrawPixel(screen, i, j, r, g, b);
i++;
}
///////////////// Code end

Note the // commented line in the middle of the code. For some reason, when the code is in its current state, I get expected results. But when the commented line is substituted in for the (apparently equivalent, or so I thought) line above it, the variable m seems to be equal to zero.

Why does C++ think 0.25 is not equal to 1/4?!

Any help much appreciated.

• : Why does C++ think 0.25 is not equal to 1/4?!

Because 0.25 does not equal 1/4. 0.25 is a double, 1/4 is an integer. An integer cannot hold a floating point value, so it gets truncated. What does 0.25 get truncated to? 0. However, 0.25 IS equal to 1.0/4.0 or 1/4.0 or 1.0/4.
• So how can I divide one integer by another, and then multiply this by another integer, and then round the result off?

You see, I've been trying to define m = t*grad, but m always gets set to zero for some reason (- even when grad*t > 1).

: : Why does C++ think 0.25 is not equal to 1/4?!
:
: Because 0.25 does not equal 1/4. 0.25 is a double, 1/4 is an integer. An integer cannot hold a floating point value, so it gets truncated. What does 0.25 get truncated to? 0. However, 0.25 IS equal to 1.0/4.0 or 1/4.0 or 1.0/4.
:

• : So how can I divide one integer by another, and then multiply this by another integer, and then round the result off?

instead of a/b*c you simply write a*c/b

:
: You see, I've been trying to define m = t*grad, but m always gets set to zero for some reason (- even when grad*t > 1).
:
:
:
: : : Why does C++ think 0.25 is not equal to 1/4?!
: :
: : Because 0.25 does not equal 1/4. 0.25 is a double, 1/4 is an integer. An integer cannot hold a floating point value, so it gets truncated. What does 0.25 get truncated to? 0. However, 0.25 IS equal to 1.0/4.0 or 1/4.0 or 1.0/4.
: :
:
: