This code prints coordinates for a square that another program uses. For space's sake I have cut out all the other program's code, but I believe it is a simple syntax mistake with my if() statements. I have followed the rules and looked just about everywhere and followed all of the C guidelines, but I keep getting 100 of the first coordinates followed by "no value". It seems that the program thinks ctr is not 0, where it is clearly defined.... Any reply would be appreciated.

int main()
{
        int ctr;
	int stopctr=0;
        double	xcoord[1];
	double	ycoord[1];
	xcoord[0]=5;
	ycoord[0]=-5;
	ctr=0;
	do{
		if(ctr==1)
		{
			xcoord[0]=-5;
			ycoord[0]=-5;
		}
		else if(ctr==2)
		{
			xcoord[0]=-5;
			ycoord[0]=5;
		}
		else if(ctr==3)
		{
			xcoord[0]=5;
			ycoord[0]=5;
		}
		else if(ctr=4)
		{
			xcoord[0]=5;
			ycoord[0]=-5;
		}
		else{}
		if((xcoord[0]==-4.9)&&(ycoord[0]==-5))
			ctr=1;
		else if((xcoord[0]==-5)&&(ycoord[0]==4.9))
			ctr=2;
		else if((xcoord[0]==4.9)&&(ycoord[0]==5))
			ctr=3;
		else if((xcoord[0]==5)&&(ycoord[0]==-4.9))
			ctr=4;
		else{}
                printf("(%f,%f)\n",xcoord[0],ycoord[0]);
                if(ctr==0)
	{
		xcoord[0]=xcoord[0]-0.1;
		ycoord[0]=ycoord[0]+0;
	}
	else if(ctr==1)
	{
		xcoord[0]=xcoord[0]+0;
		ycoord[0]=ycoord[0]+0.1;
	}
	else if(ctr==2)
	{
		xcoord[0]=xcoord[0]+0.1;
		ycoord[0]=ycoord[0]+0;
	}
	else if(ctr==3)
	{
		xcoord[0]=xcoord[0]+0;
		ycoord[0]=ycoord[0]-0.1;
	}
	else
	{
		printf("no value\n");
	}
	stopctr=stopctr+1;
	}while(stopctr<100);
}

Edited 4 Years Ago by ben25x: lining up pasted code

....besides that [if(ctr=4)]. That is [if(ctr==4)]. But I've narrowed the problem down to the second section of if()s. Am I not using "&&" right?

I see your code makes comparisons with doubles - which is quite hazardous. Floating point numbers can't represent all values - they have to (very closely) approximate some of them.

The "cleanest" way to work with numbers that must be compared, is to use a multiplier, and then cast them to integers. So 100.68 would become 10068, for example. Do that RIGHT AWAY, with every float value. Then, for your output, cast it back to a double, and divide it by the same power of ten that you multiplied it by.

Another way, is to make your comparisons within a small range, instead of a fixed value. if double > 4.89 && double < 4.91 kind of logic.

If you google for "problem comparing floats", you'll find a lot more info on it.

This question has already been answered. Start a new discussion instead.