As you see, new numbers start coming into the float, fiving me a problem is a smaller number is used.
So my question is this. either how can I stop numbers besides 0 coming in?
Is there some math formula I can use to chage the new non-zero number to zero?
This is a common misconception people have about floating point numbers.
The number 1.23456 is in decimal, but floats are in binary. 1.23456 can't be precisely represented in binary, only approximately. The numbers you see coming from the right are the error between the binary and the decimal representation.
There's a few methods you can use to fix this. From best to worse:
1. Use a better conversion algorithm. I believe the standard method is to actually perform the operation described by the floating point representation, in decimal.
2. Use a double. This may not actually solve it.
3. Multiply by 10^5 and assign to an integer.
Where I pointed out the problem, it should be 2 - 3 - 3, however my statement i=b seems to be disregarded the third time through, therefore not allowing my if statment to stop the loop.
Sorry, I may be just missing something here, but I don't see how those will help.
It should be that I is assinged B's value, which is currently 3. But as you see from my run, that I = 2 before, and after my i=b; statement. However, on others, such as line 2, I goes from 1 to 2, as expected when given the value 2.3.
So am I missing something, or was I not clear in my last post? (sorry if it is either)
2.23 is actually being represented as 2.229999... By the third step, b is 2.9999..., which is rounded and printed as 3. If you first <<std::setprecision(20) (#include <iomanip>), you'll see what I mean.
There's really no way around this, other than method #1 I described above, or using sprintf() or std::stringstream.
Well, I guess I'll be going with method one sometime in the future.
Thanks a ton for your help!
Before I mark this thread as solved, can you tell me what file sprintf/snprintf() comes from? Also, is it a C function? (I ask because of the printf part)
Just like you can send integers, floats, etc. to std::cout using the << operator, you can send the same things to an std::stringstream and get the contents using std::stringstream::str().
There are also rounding algorithms to take a number like 2.999 and round it to the nearest integer value (3). See the following link for some reading and some rounding algorithms: http://www.cplusplus.com/forum/articles/3638/
Good luck!
As you see from the last example, it does't work precisely, as the last one should round up to 2.
Still, as long as it's .5+ it rounds up, if not it rounds down.
Well, I thought I did. But if I don't, please help me to understand. Unless you just don't want to help, then there is no need for you to respond to this post.