2
« on: November 07, 2015, 04:35:12 am »
Hello f.ds,
I need to write a small program for school that calculates the nearest thing to a natural square root of a natural number. Unfortunately, no if is allowed and I have no Idea how to make it work without it. You can see my code and further restrictions below:
int main()
{
int input;
int result;
int addition;
int helper;
/* The sum of n successive odd numbers is a squared number. For example 1 + 3 = 4, 1 + 3 +5 = 9.
The purpose of this program is to show the nearest naturel square root of "input". For example if the input is 17 the result should be 4.
Restrictions: Only one while loop is allowed. No If. Only addition, !=, ==, <, >, >= and <= are allowed
*/
addition = 1; // To get odd numers, the addition has to start at 1
helper = 1; // Since the addition starts at 1, this has to start at 1 aswell
result = 1; // Same reason as above
cout << "Enter a number X >= 1: ";
cin >> input;
while(input > helper) // This ensures that the while loop ends on time
{
addition = addition + 2; //This creates the next odd number
helper = helper + addition; //This creates the next squared number
result++; // This increases the result by one, because the helper now represents the next squared number
}
cout << "The ";
cout << result;
cout << " is the natural square root of ";
cout << input << endl;
}
My problem is that if I type in the 17 for example, it gives out the 5, but it should give out the 4.
Any Ideas how to fix it?
Thank you in advance!
EDIT: I solved the problem, maybe i will fix the wrong code here later. Thank you all for your help!