Thread: Float discrepencies

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    81

    Float discrepencies

    I have a question about adding floats. Seems that when I do the following code:

    Code:
    #include <climits>
    #include <iostream>
    using namespace std;
    
    int main()
    {
      float x;
      int i;
      x = 1.0;
      i = 0;
      while (i < 1000)
      {
        cout << "x = " << x << endl;
        x = x + .0001;
        i++;
      }
      return 0;
    }
    the end result is not right. At 1.0301 it's fine, but then it adds an extra one at the end for the next float, i.e. 1.03021. It then does it again at 1.09031, where the next one is 1.09042 (where the last digit 1 and 2 respectively are not even supposed to be there).

    I'm thinking that this is because the numbers are of type float and I've read that "float is often merely an approximation of the desired value"

    Am I right or is there another reason? This may seem like a silly question, but I would like to understand why it behaves like it does.

    As always, any comments is appreciated.

  2. #2
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378

    Is this what your after...

    Greetings,
    using the iomanip class enables you to format your code.
    Code:
    #include <climits>
    #include <iostream>
    #include<iomanip>	//used for format manipulation
    using namespace std;
    
    int main()
    {
      float x;
      int i;
      x = 1.0;	//this is not an integer
      i = 0;
      for (i = 0; i < 1000; i++)
      {
        cout << "x = " << setprecision(4) <<fixed<< x << endl;	//sets decimal right 
    															//only 4 spaces
        x = x + .0001;
      }
      return 0;
    }
    ps. your right numbers l(eg; PI is approx.)

    I hope this helped.
    cj
    "Be formless, shapeless, like water... You put water into a cup, it becomes the cup, you put water into a bottle, it becomes the bottle, you put it in a teapot, it becomes the teapot... Now water can flow, or it can crash, be water my friend."
    -Bruce Lee

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    81
    Thanks guys!! It answered my question!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-13-2009, 03:25 PM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM