mercredi 7 juin 2017

Why is rand() giving me numbers outside of my defined interval? (It worked fine yesterday)

I am generating random integers between 1000, and 11000. However they must have a mean of 6000. I used this snip of code in my program yesterday and it worked just fine, but now it gives me huge numbers as if my interval doesn't matter.

Edit: Stripped the code down a bit for easier reading.

srand(time(NULL));
int k = 5;
int cTotal = 0;
int cAverage = 0;

  struct process {
    int pid; // process id
    int cycles; // number of cycles required to complete the process
    int mSize; // size of the memory footprint
};

    for (int i = 0; i < k; i++) {

        processes[i].pid = i; // set the unique identifier of the process.

        // If statements for determining the number cycles in each process
        if (k == 0) {
            processes[i].cycles = 6000; // if the user decides to try only one process, the average must be 6000, so assign 6000 as its value.
            cTotal += processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 0) { // if we have more than 1 process and  it happens to be the first one, go ahead and randomize it since we can adjust the average after the first iteration.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else if (cAverage == 6000 && i != k - 1) { // if the average is already at 6000, it's safe to choose any random number so do that unless this is the last iteration of the loop.
            processes[i].cycles = rand() % 11000 + 1000; //update the total number of cycles, and the average.
            cTotal += processes[i].cycles;
            cAverage = cTotal / (i + 1);

        } else {
            processes[i].cycles = (6000 * (i + 1)) - cTotal; // set the number of cycles such that the average will be 6000
            cTotal = cTotal + processes[i].cycles; //update the total number of cycles, and the average.
            cAverage = cTotal / (i + 1);
        }
    } //for




Aucun commentaire:

Enregistrer un commentaire