[fpc-pascal] C translation question

Bernd Oppolzer bernd.oppolzer at t-online.de
Sun Oct 23 22:31:43 CEST 2016


What I wanted to say:

when translating the for loop to Pascal, you are in danger of introducing
logic errors, because the Pascal for loop is kind of restricted compared to
the C for loop (which is in fact simply a while loop with another 
notation).

But if you translate the C for loop to a while loop first, then you can
translate this loop in a straightforward manner to Pascal, and the 
probability
of inserting logic errors is much lower.

Kind regards

Bernd


Am 23.10.2016 um 22:20 schrieb Bernd Oppolzer:
> it might help if I translate the C for loop into an equivalent
> while loop for you, (and eliminating the ++ construct),
> simply mechanically, without knowing anything about the application.
>
> This results in:
>
> int pnpoly (int nvert, float *vertx, float *verty, float testx, float 
> testy)
> {
>   int i, j, c = 0;
>
>   i = 0, j = nvert-1;
>
>   while (i < nvert)
>   {
>     if (((verty [i] > testy) != (verty [j] > testy)) &&
>          (testx < (vertx[j] - vertx[i]) * (testy - verty [i])
>           / (verty [j] - verty [i]) + vertx [i]))
>        c = !c;
>
>     j = i;
>     i = i + 1;
>   }
>
>   return c;
> }
>
> HTH,
>
> kind regards
>
> Bernd
>
>
>
> Am 22.10.2016 um 11:06 schrieb Ryan Joseph:
>> I’m trying to translate a function from C (taken from 
>> http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html) 
>> and although I think I got it correctly it’s not behaving 100% 
>> accurately so I’m not sure if it was my translation or not. The “for” 
>> statement is pretty confusing to my eyes despite the author of the 
>> function giving a description of his code.
>>
>> Does anyone spot any errors with my translation?
>>
>> int pnpoly(int nvert, float *vertx, float *verty, float testx, float 
>> testy)
>> {
>>    int i, j, c = 0;
>>    for (i = 0, j = nvert-1; i < nvert; j = i++) {
>>      if ( ((verty[i]>testy) != (verty[j]>testy)) &&
>>       (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / 
>> (verty[j]-verty[i]) + vertx[i]) )
>>         c = !c;
>>    }
>>    return c;
>> }
>>
>>
>> function TPolygonHelper.ContainsPoint (point: TPoint): boolean;
>> var
>>     i, j, c: integer;
>> begin
>>     i := 0;
>>     j := high(self);
>>     c := 0;
>>     for i := 0 to high(self) do
>>         begin
>>             j := i + 1;
>>             if ((self[i].y > point.y) <> (self[j].y > point.y))
>>                     and (point.x < (self[j].x - self[i].x) * (point.y 
>> - self[i].y) / (self[j].y - self[i].y) + self[i].x) then
>>                 c := not c;
>>         end;
>>     result := c <> 0;
>> end;
>>
>> Regards,
>>     Ryan Joseph
>>
>> _______________________________________________
>> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
>> http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
>




More information about the fpc-pascal mailing list