Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ float to int

Tags:

c++

Maybe, it's very simple question but I couldn't get the answer. I've been searching quite a while ( now Google think that I'm sending automated queries http://twitter.com/michaelsync/status/17177278608 ) ..

int n = 4.35 *100;
cout << n;

Why does the output become "434" instead of "435"? 4.35 * 100 = 435 which is a integer value and this should be assignable to the integer variable "n", right?

OR Does the C++ compiler cast 4.35 to integer before multiplying? I think it won't. Why does the compiler automatically change 4.35 to 4.34 which is still a float??

Thanks.

like image 587
Michael Sync Avatar asked Jun 27 '10 16:06

Michael Sync


People also ask

How do I convert a float to an int in C?

The way to get the value is either the lib function int floor(float) or (for roundingup) int ceil(float).

How do you convert a float to an integer?

A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function.

Is int and float equal in C?

Assigning an integer to float and comparison in C/C++ The integer is a data type used to define a number that contains all positive, negative or zero non-fractional values. These cannot have decimals. Float is a data type used to define a number that has a fractional value. These can have decimals also.

Can we store float into integer variable in C?

So you cannot store a float value in an int object through simple assignment. You can store the bit pattern for a floating-point value in an int object if the int is at least as wide as the float , either by using memcpy or some kind of casting gymnastics (as other answers have shown).


2 Answers

What Every Computer Scientist Should Know About Floating-Point Arithmetic

That's really just a starting point, sadly, as then languages introduce their own foibles as to when they do type conversions, etc. In this case you've merely created a situation where the constant 4.35 can't be represented precisely, and thus 4.35*100 is more like 434.9999999999, and the cast to int does trunc, not round.

like image 163
Nick Bastin Avatar answered Sep 22 '22 17:09

Nick Bastin


If you run this statement:

cout << 4.35

Dollars to donuts you get something approximately like 4.3499998821 because 4.35 isn't exactly representable in a float.

When the compiler casts a float to an int it truncates.

To get the behavior your expect, try:

int n = floor((4.35 * 100.0) + 0.5);

(The trickyness with floor is because C++ doesn't have a native round() function)

like image 45
Donnie Avatar answered Sep 22 '22 17:09

Donnie