I was trying to make a function to take the square root of a number (which does not work completely, yet), but while I was coding it, I found an strange "error", this is the code:

#include <iostream>
#include <cstdlib>
 
using namespace std;
  
int main()
{        
    double number;
    cin >> number;
    double i2 =0, i=0;
    while( (i*i) < number )
    {
        if (i == 0)
            i = 0.1;
        else
            i *= 2;
    }
    
    i2 = i/4.0;
    while ((i * i) > number)
    {
        i -= i2;
        i2 /= 2.0;
    }
    cout << i << endl;
    system("PAUSE");
   return 0;
}

Everything was working properly until I realized that the last loop iterated one more time than I expected. I tried to use 4 as "number", it would eventually become 2, which then would be tested in: while ((i * i) > number), I supposed that it would make the loop become false and end with i having a value of 2, but it instead iterated one more time, leaving i with a value of 1.8, finally I tried using floats (which seemed a waste of time for me, since double is more precise, or at least that is what I had been told), my surprise was that it DID work, and I do not know why there is a problem using doubles. I would like to know if there is a special reason. Thank you for reading ;).

PD: I posted the "bad" code so you could check it.

Since doubles are rarely exact, probably your loop counter is wrong. For example when you think i=4 it's probably i=3.9999902 or something like that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.