Taharix Taharix - 2 months ago 9
C++ Question

c++ data types and how they are represented

I have been playing around with the Babylonian square root algorithm from an assignment in my intro to programming class.
The program works fine and gives pretty accurate answers. My question stems from something weird happening in the line (while guess != result )
I wrote that while statement to check the two terms, and as soon as they are identical, break the loop. However, if you input, say 50 as the starting number, the loop checks two identical numbers three times before it breaks out, instead of once. Is this because there are more numbers being crunched in the background, that the double data type can't display? I know double can go up to 15 decimal places. I hope i'm wording this in a way that is understandable, if anyone needs clarification just ask.
PS- if anyone has tips to help make my code cleaner, please do let me know, I'm trying to learn how to format my code to be as readable as possible.

#include <iostream>

using namespace std;

int main()
{
double input, // Users number
guess = 2, // First guess, always 2 at beginning
result, // altered guess, becomes guess 1 when repeated
r; // input divided by guess

int steps = 1, // keeps track of step number, for debugging
loop = 1; // controls continue loop

string error_1 = " Warning: input is negative, please pick a new one";

while (loop == 1)
{
cout << "--Babylonian Square Root Algorithm--" << endl;
cout << "Type a positive number to find its square root: ";
cin >> input;

if (input >= 0)
{
while (guess != result) // test here for within 1%
{
r = input / guess;
result = (guess + r) / 2;
// DEBUG
cout << "-------" << endl;
cout << " Step # " << steps << endl;
cout << "-------" << endl;
cout << " R) " << r << endl;
cout << " Guess) " << guess << endl;
cout << " Result) " << result << endl;
steps++;

guess = result;
result = (guess + r) / 2;
cout << result << " is the approximate square root of " << input << endl;
//DEBUG
cout << " Steps required: " << steps - 1 << endl;
}
else
{
cout << error_1 << endl;
}
cout << "Continue? (Yes = 1, No = 0)" << endl;
guess = 2;
result = 0;
steps = 1;
cin >> loop;
cout << "------------------------------------------------------" << endl;
}
return 0;
}
}

Answer

"guess" and "result" are "double" type, it has higher precision than you can see with default cout floating point digit display length.

you think that the numbers are same, but they are not. farther you go from decimal point you can see the difference.

Solution 1: change the cout decimal number display range to a longer value, so that you can see that the numbers are actually different, so while loop didn't break. use cout.precision(17); at the start of code.

Solution 2: change the datatype of guess & result to "float"

Comments