mardi 7 décembre 2021

C SRAND - First random value not random [duplicate]

I'm working on a group project where I need to generate a set of random numbers, however, the values are staying the same. The values should be between 0 and 1 in a float value.

The code is as follows:

srand((unsigned int) time(0));

float randNumber = (float) rand() / (float) (RAND_MAX) * (float) 1;
if (randNumber < 0.05) {
    state = STATE_HEALTHY;
} else if (randNumber > 0.05 && randNumber < 0.15) {
    state = STATE_INFECTED;
} else {
    state = STATE_HEALTHY;
}
printf("[%i][%i] Generated Number: %.2f  |  State: %i\n", X_INDEX, Y_INDEX, randNumber, state);

If I put the rand() in a printf at the end underneath the last printf the number returned is always random.

The end goal for this is the output below should have a randomly generated number for each index (of x and y)

[0][0] Generated Number: 0.20  |  State: 0
[0][1] Generated Number: 0.20  |  State: 0
[1][0] Generated Number: 0.20  |  State: 0
[1][1] Generated Number: 0.20  |  State: 0

How would it be possible to generate a random number for cell?

Edit: After using the suggestion by @drescherjm I am faced with the issue of the first value not being random but instead being incremented very slowly by one, see below for two outputs after the suggestion.

[0][0] Generated Number: 0.25  |  State: 0
[0][1] Generated Number: 0.79  |  State: 0
[1][0] Generated Number: 0.37  |  State: 0
[1][1] Generated Number: 0.97  |  State: 0

[0][0] Generated Number: 0.25  |  State: 0
[0][1] Generated Number: 0.38  |  State: 0
[1][0] Generated Number: 0.00  |  State: 0
[1][1] Generated Number: 0.25  |  State: 0

EDIT: This is my attempt for the minimal reproducible example. Below is the code I made to reproduce this:

Main.c

    #include "header.h"

int main() {
    srand((unsigned int) time(NULL));
    test();
    return 0;
}

Test.c

#include "header.h"

void test() {
    for (int i = 0; i < grid_w; ++i) {
        for (int j = 0; j < grid_h; ++j) {
            grid[i][j] = randomNumTest(i, j);
        }
    }
}

randomNumTest.c

#include "header.h"
    
    int randomNumTest(int x, int y) {
        float randNumber = (float) rand() / (float) (RAND_MAX) * (float) 1;
    
        printf("[%i][%i] Generated Number: %.2f\n", x, y, randNumber);
    
    }

Header.h

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

#define grid_h 2
#define grid_w 2

void test();

int randomNumTest(int x, int y);

int grid[grid_h][grid_w];



Aucun commentaire:

Enregistrer un commentaire