views:

125

answers:

1

I've been tasked to draw eight lines, forming something like a regular eight-point star, with Bresenham's line drawing algorithm. It was to be done in Delphi language. As I'm not really good at canvas drawing, I simply copy-pasted the algorithm from Wikipedia for Object Pascal, with minimum changes.
But the Wikipedian algorithm had the Sign(x) function, that wasn't included in Delphi standard libraries, so I had to write it myself:

 function Sign(x:integer):integer;
begin

if x=0 then  Result:=0;
if x>0 then Result:=1;
else Result:=-1;
end;

Everything worked fine, but I could only operate in first two quadrants, other coordinates were mirrored. I changed function to display errors:

function Sign(x:integer):integer;
begin

if x=0 then  Result:=0;
if x>0 then Result:=1;
if x<0 then Result:=-1 else begin
Form1.Label5.Caption:='Err!';
Result:=2;
end;

end;

I used this function as following:

 sx:=Sign(x1-x0);
 sy:=Sign(y1-y0); 

x0,x1,y0,y1 are coordinates of line begin and end points. I am confused, it seems that sometimes x1-x0 and y1-y0 are not not less, more or equal to zero, but fall under the 4th 'else' statement. Could you please explain the humble beginner, why does it happen?

P.S. I got that program to work, by changing the 4th 'else' statement to Result in 1, but still confused of this situation.

Thank you in advance.

+4  A: 

You're missing an else before the second if. So 0 falls both into the =0 case and the else case of >0.

function Sign(x:integer):integer;
begin    
    if x=0 then  Result:=0
    else if x>0 then Result:=1
    else Result:=-1;
end;

And there is a Sign function in the Math unit.

And you could have tested your function with parameters -2,-1,0,+1,+2 to see what happens.

CodeInChaos
Um, thanks, coudnt google up the name of that unit.Accepted.
Nordvind
@norvind: If you want to accept it, click the checkmark under the score control.
Mason Wheeler
@Norvind, don't ask Google what functions Delphi has. Ask Delphi. Use your favorite text-searching tool to search the Delphi source files for the function you're interested in. Delphi comes with a `grep` command-line tool, and its "find in files" GUI command is serviceable, too.
Rob Kennedy
In addition to Rob Kennedy's remark, I have found it *extremely* helpful, in Windows 7, to 1) include the `Source\Win32` subfolder in the Windows search index, and to 2) include *.pas files in the plain text-mode file type category, so that I can search for (a source file containing) an identifier by pressing the Windows button and typing the first letters of its name.
Andreas Rejbrand
But in this case -- is it a surprise that the sign function is called `sign` in Delphi? And is it surprising that it is defined in the `math` unit?
Andreas Rejbrand