Board index » cppbuilder » Problem Drawing on Canvas

Problem Drawing on Canvas

I have the following code, which draws ellipses (circles) of random
sizes at random points on the canvas.
The code works fine.

    for (i=0; i<100; i++ )
    {
        left = 1 + rand() % 480;
        top = 1 + rand() % 290;
        diameter = 1 + rand() % 4;
        Canvas->Ellipse(left, top, left+diameter, top+diameter);
    }

My problem is this:  I want to replace each ...rand()... statements
with calls to functions that return the appropriate random numbers.
Example:
left = getX();
//following is getX():
int __fastcall TForm1::getX( void )
{
    srand(time(NULL));
    return 1 + rand() % 480;

Quote
}

When I do so, only the last ellipse in the loop is drawn
on the canvas.

1) Why does this behavior happen?
2) Is there any way to prevent the unwanted behavior, but keep
my function calls?

Thanks!
Steve

 

Re:Problem Drawing on Canvas


Hi !

Steve & Jeni Murphy <tio...@uswest.net> a crit dans le message :
386AD153.A350...@uswest.net...

Quote
> file://following is getX():
> int __fastcall TForm1::getX( void )
> {
>     srand(time(NULL));
>     return 1 + rand() % 480;
> }

> When I do so, only the last ellipse in the loop is drawn
> on the canvas.

    Your problem is that your machine is too fast ! :-)
    Take the "srand(time(NULL));" out of your GetX function
    and all should be ok ...

    The problem is that the srand initialize the random generator with
    the same number each time the GetX function is called, so the GetX
    function return always the same number and you draw 100 exactly similar
    elipses ...

    An srand should be done only once, do it before you start your loop, by
example.

    Hope this will help,

        Zylwee

Re:Problem Drawing on Canvas


Merci bien et bonne annee!
Quote
Patrick Berthon wrote:
> Hi !

> Steve & Jeni Murphy <tio...@uswest.net> a crit dans le message :
> 386AD153.A350...@uswest.net...
> > file://following is getX():
> > int __fastcall TForm1::getX( void )
> > {
> >     srand(time(NULL));
> >     return 1 + rand() % 480;
> > }

> > When I do so, only the last ellipse in the loop is drawn
> > on the canvas.

>     Your problem is that your machine is too fast ! :-)
>     Take the "srand(time(NULL));" out of your GetX function
>     and all should be ok ...

>     The problem is that the srand initialize the random generator with
>     the same number each time the GetX function is called, so the GetX
>     function return always the same number and you draw 100 exactly similar
>     elipses ...

>     An srand should be done only once, do it before you start your loop, by
> example.

>     Hope this will help,

>         Zylwee

Other Threads