0

I was tinkering with the bounce function in pset4 trying to get the ball the bounce randomly around the window. I am getting stuck with PRNG. I just can't seem to get it to work using the srand48 function. I have made it work using just the simple rand function that we used previously. This begs the question is it really preferable to use srand48 in this case? Here is my code.

   //standard libraries
   #include <stdio.h>
   #include <time.h>
   #include <stdlib.h>

   // Stanford Portable Library
   #include "gevents.h"
   #include "gobjects.h"
   #include "gwindow.h"


   int main(void)
   {
    srand48(time(NULL));
    // instantiate window
    GWindow window = newGWindow(320, 240);

    // instantiate circle
    GOval circle = newGOval(0, 110, 20, 20);
    setColor(circle, "BLACK");
    setFilled(circle, true);
    add(window, circle);

    // initial velocity
    double heightvelocity = lrand48()%4+2.0;  //number between 2 and 5
    double widthvelocity = (5.0-heightvelocity)+1;  //number between 1 and 4

    // bounce forever
    while (true)
    {
        // move circle along x-axis
        move(circle, widthvelocity, heightvelocity);

        // bounce off right edge of window
        if (getY(circle) + getHeight(circle) >= getHeight(window))
        {
            heightvelocity = -heightvelocity;
        }

        // bounce off left edge of window
        else if (getY(circle) <= 0)
        {
            heightvelocity = -heightvelocity;
        }

     // bounce off right edge of window
    else if (getX(circle) + getWidth(circle) >= getWidth(window))
    {
        widthvelocity = -widthvelocity;
    }

    // bounce off left edge of window
    else if (getX(circle) <= 0)
    {
        widthvelocity = -widthvelocity;
    }


        // linger before moving again
        pause(10);
    }
}
1
  • Just make that thing do the work, its not necessary to use srand(), grader will not throw error on that issue, but that's suggested to make you learn something new.
    – sinister
    Oct 26, 2014 at 15:17

1 Answer 1

1

Add the following line before your #include statements:

#define _XOPEN_SOURCE

1
  • Perfect! Thank you so much Oct 26, 2014 at 19:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .