GuineaPig wrote:

>

> Hello,

>

> I'm (very) new to c++ and I'm having trouble understanding why this doesn't

> work. Here's some testcode:

>

> #include <iostream.h>

>

> int main()

> {

> float test;

> unsigned int test2;

> test = 1.8;

> cout << "\n" << test*100.0 << endl;

> test2 = static_cast<unsigned int>(test*100.0);

> cout << "\n" << test2 << endl;

>

> }

>

> The strange thing is that the program returns 180 on the first cout (as

> expected) but it returns 179 on the second ???
That's because you computer cannot store the value 1.8 exactly.

It may be stored as 1.7999999999999999... or 1.80000000000001 or

something like that.

Multiplying with 100 gives 179.9999999999999999... or

180.0000000000001 or something like that.

When operator<< outputs a floating point number, this number is

rounded to x decimal digits (usually x equals 6, if nothing else specified).

So rounding 179.99999999999999 to 6 digits yields (surprise) 180.000000

Rounding 180.00000000000001 to six digits also yields 180.000000

(and of course the superflous decimal digits are not output).

Note: The number was *rounded* in order to be printed.

The cast does a very different thing. The cast truncates the

decimal digits from a number.

179.9999999999999999 is close to 180.0, but that doesn't

matter. Truncating the decimal digits still leaves you with

179.

180.0000000000000001 is also close to 180.0, but this time

truncating the decimal digits leaves you with 180.

The difference: rounding gives a different result then truncating.

> If I make test 1.7, I get 170 on the first and second cout ???

> I tried a whole bunch of other values... Sometimes I'm getting what I

> expected, sometimes not...
It depends on how the numbers are stored. Note: A computer cannot

store every floating point number exactly. In the range 0 .. 1

there are indefinitly many floating point numbers and your computer

only has a finite memory.

--

Karl Heinz Buchegger

http://www.velocityreviews.com/forums/(E-Mail Removed)