Problem with decimals

Feb 12, 2014 at 9:41pm
Hy,

I'm having a prob, with a program that's supposed to print values of y=2x+5, for x from -10 to 10.
I know it's really simple code, but it gets me a decimal value of i...when it should just subtract 0.2, so it ends up like -4.60001, or 7.79999...http://prntscr.com/2rxep2

Here is the code:

1
2
3
4
5
6
7
8
9
  #include <iostream>

using namespace std;

int main()
{   for(float i(-10); i<=10; i+=0.2)
        cout<<"Za i="<<i<<" : "<<2*i+5<<endl;
    return 0;
}
Feb 12, 2014 at 10:00pm
The output of your code is normal, I'm not sure what more you are looking for. If you don't want decimal numbers then use integers or use output stream manipulators:
http://en.cppreference.com/w/cpp/io/manip/setprecision

std::cout << std::fixed << std::setprecision(0) << "Za i = " << i << " : " << 2 * i + 5 << std::endl;
Last edited on Feb 12, 2014 at 10:01pm
Feb 12, 2014 at 10:04pm
You've tested this code and got the normal output ?
Because look at this: http://prntscr.com/2rxep2

And decimals don't bother me..they need to be cuz there is a step of 0.2.....I'm sorry if I have expressed myself wrong in previous post.

What bothers me is those 0's and then 1 in output eg. -4.60001.

And thank you for your reply.
Feb 12, 2014 at 10:07pm
Do not use float as iterating variable. 0.2 is about 1/5, so stepping from -50 to 50 would give you how many steps? More or less than your loop?


Wait, "0.2 is about 1/5"? Isn't it exactly so? No. Floating point numbers are not continuous; they are discrete, with limited precision. You do see that imprecision in your results. I guess that demostrating this feature is a purpose of your homework(?).

You can use tools from <iomanip> to format the output.
Feb 12, 2014 at 10:16pm
Floating-point numbers are inexact.
Not every real number can be represented perfectly as a float or double, so we have to stick with rough approximations, which is what you're seeing.
For instance, at least on my machine, setting float f = 0.02; will actually make f closer to 0.2000000029802322387695312500.

In your case, you can either reduce the precision of cout:
cout.precision(3); // Display 3 digits

or you can switch to double (which has more precision, but it's still inexact) instead of float.

In either case, your i = 0 is still going to be messed up, because you start at i = -10 and then you keep adding approximations of 0.2, so you'll actually end up "missing" 0 by a very small margin (I end up with -5.03957e-006).
Last edited on Feb 12, 2014 at 10:17pm
Feb 13, 2014 at 1:47pm
Great, thank you for your explanation long double main
I'll just set the digits to display then.

Thanks to all of you
Topic archived. No new replies allowed.