Problem with math program

So I have this program that allows one to find the square root of a number except it does not do quite that. When I run it, the square root it gets is always 0.

Here is the program so far:
[code]#include <iostream>

using namespace std;

int main()
{
string shallwestart;
cout << "Welcome to this program of finding square roots of numbers.\nShall we start?(Y/N)";
cin >> shallwestart;
if (shallwestart == "y")
{

iff:
cout << "Ok! Please enter the number you want square-rooted: ";
long start1;
long start2;
cin >> start1;
start2 = start1;
long halfstart;
halfstart = start1/2;
for (long x=halfstart;x--;start1=x*x)
{
halfstart--;
}
cout << "The square root of " << start2 << " = " << halfstart << "!";
}
else if (shallwestart == "Y")
{
goto iff;
}
else if (shallwestart == "n")
This piece of code
1
2
3
4
for (long x=halfstart;x--;start1=x*x)
{
halfstart--;
}
executes while x>0. If x==0, so is halfstart.

Read about for loop: http://www.cplusplus.com/doc/tutorial/control/
Also, why are your numbers integer? Is it your intention?
Do not post the same problem twice. Its against the forum rules.
http://www.cplusplus.com/forum/beginner/58270/
I am not sure that this code is going to calculate the square root:
1
2
3
4
5
6
7
8
cin >> start1;
start2 = start1;
long halfstart;
halfstart = start1/2;
for (long x=halfstart;x--;start1=x*x)
{
halfstart--;
}


It's executed while x-- is true meaning for all values x>0 since x could not be negative (no check for that but we will pass it for now).

For example if user enters 4 so start1 = 4 so is start2. halfstart = 2.
x and halfstart are following the same decremental step so they end up always 0 both.
This examples loops give:
x halfstart
loop 1: 2 2
loop 2: 1 1
loop 3: 0 0
For each step you increment start1=x*x but you n ever use it.
You are not using start2 at all (I think you don't want this).

I think you should study a bit the way for loops are intended to work.

You also use goto! Really bad choice. DON"T use them at whatevver cost. Sometimes they seem like the easiest way but don't even get to the point of validating their use. There is always an alternative for this. Find it out and use that instead.
Topic archived. No new replies allowed.