1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Some problems with C++ - Need Help

Discussion in 'C++' started by szoki, May 2, 2011.

  1. szoki

    szoki New Member

    Joined:
    Mar 22, 2011
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    #include <iostream>
    using namespace std;
    void main()
    {
    long int n;
    n=0;
    float x,y;
    do
    {
    n++;
    x=1+1/(float)n;
    y=1-1/(float)n;
    }while (x!=y);
    cout<<n<<" "<<x<<" "<<y;
    }
    
    This is the code with mistake in arithmetic precision.
    What's wrong with the code?
    And if i put the "cout" line before while, program doesn't stop.Why?
    When x & y will be same,or do they ever will be same?
    Can any1 answer my questions?

    Thanks in advance.
     
  2. DRK

    DRK New Member

    Joined:
    Apr 13, 2012
    Messages:
    44
    Likes Received:
    3
    Trophy Points:
    0
    The program will stop, but when you put cout into while loop, it works much slower, because it has to display data on the screen (it this case it's over 33 million lines!).


    Just run the program and you will see the result. For my compiler, x and y were equal when n reached value of 33554432 .


    There's nothing wrong. Read more: en.wikipedia.org/wiki/Floating_point#Accuracy_problems
     

Share This Page