This topic is now archived and is closed to further replies.


modulus operator %

Recommended Posts

okay, i'm sure this has been answered several times, but can someone explain to me why i get an output of 3 instead of 4 for the following piece of code?
void main()
	float number = 33.14f;

	float exnumber = number * 100.0;

	int hundredths = (int)(exnumber)%10;

	cout << hundredths << endl;	//returns 3, shouldn't it be 4?
Edited by - a2k on March 19, 2001 5:33:58 PM

Share this post

Link to post
Share on other sites
The problem is the ".14" part of 33.14. .14 = 14/100 = a fraction whose decimal representation repeats infinitely(.0714285714285714285714285714285). The floating point representation of 33.14 therefore has to make an estimate of the actual number represented, causing loss of precision.

I think your confusion is that you may be thinking, "When I multiply by 100, I just shift the decimal point over two places." Well, that's true in decimal. In binary, you can shift your decimal point when you multiply by powers of two; since 100 is not a power of two, an actual multiplication takes place. Because of this multiplication, the loss of precision in the original float is magnified.

If you use an intermediate integer and your debugger, you should see that int val = 33.14f * 100f = 3313, not 3314. If you used an intermediate double instead of a float, you'll see that the value of 100.0f * 33.14f = 3313.9999389648. When you cast to integer, you truncate the fractional part (no rounding takes place).

The solution is to always add 0.5 before you want to cast to an integer and round. Adding this to your program will make it work:
int hundredths = (int)(exnumber + 0.5 )%10;

edit = I actually said that a repeating number is irrational in the original post. My high school math teacher is rolling in his grave (if he's not still alive).

Edited by - Stoffel on March 19, 2001 6:20:40 PM

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
The problem is the ".14" part of 33.14. .14 = 14/100 = an irrational number that repeats infinitely(.0714285714285714285714285714285).[/QUOTE]

Ummmm, no...actually .14 is a rational number. Its value is 0.14

Now, maybe you mean its not rational in base 2, but Im not sure where you get that .07142.... number from

Share this post

Link to post
Share on other sites
Yes, you''re right, that''s what I meant--it''s not rational in base 2.

Where I got the number: smoking crack, really. I have no idea. I just have to stop posting on Mondays.

Morals of story:
- use intermediate integers when you find these problems instead of trying to do everything in one line and wondering why the output is wrong.
- if you''re having a problem with floats, try to use doubles and see if you can tell what''s going on better.
- don''t pay too much attention to posts made by me on Mondays.

Share this post

Link to post
Share on other sites