Home > Software design >  Wrong Random Numbers C
Wrong Random Numbers C

Time:04-19

I'm building a program that simulates a bus going through bus stops and picking up a random amount of passengers (0-15) the problem is that when i try to print the amount of passengers that got in on a bus stop i get a lot of numbers bigger than 15.

Here's a part of my program:

#include <stdio.h>
#include <stdlib.h>
 
struct Node {
    int data;
    struct Node* next;
};
 

void printList(struct Node* n)
{
    while (n != NULL) {
        printf(" %d ", n->data);
        n = n->next;
    }
}
 
int main()
{
    struct Node*ΤΣ_ΚΤΕΛ = NULL;
    struct Node*ΓΕΦΥΡΑ = NULL;
    ΤΣ_ΚΤΕΛ = (struct Node*)malloc(sizeof(struct Node));
    ΓΕΦΥΡΑ = (struct Node*)malloc(sizeof(struct Node));
    ΤΣ_ΚΤΕΛ->data = rand() 1;
    ΤΣ_ΚΤΕΛ->next = ΓΕΦΥΡΑ;

     printList(ΓΕΦΥΡΑ);
 
    return 0;
}

CodePudding user response:

Below has some tweaks that fix your basic issues, with explanations in the comments:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>  // you should seed the rand function to get pseudorandom numbers
                   // each time you run
 
struct Node {
    int data;
    struct Node* next;
};
 

void printList(struct Node* n)
{
    while (n != NULL) {
        printf(" %d ", n->data);
        n = n->next;
    }
}
 
int main(void)
{
    // seed the rand function with the current time, this is common
    // see link below for further info
    srand(time(NULL));
    struct Node*ΤΣ_ΚΤΕΛ = NULL;
    struct Node*ΓΕΦΥΡΑ = NULL;
    ΤΣ_ΚΤΕΛ = malloc(sizeof(struct Node));
    ΓΕΦΥΡΑ = malloc(sizeof(struct Node));

    // always check the return value of malloc
    if (ΤΣ_ΚΤΕΛ == NULL || ΓΕΦΥΡΑ == NULL)
    {
        // handle errors how you want
        fprintf(stderr, "out of memory!\n");
        exit(-1);
    }

    ΤΣ_ΚΤΕΛ->data = rand() 1;
    ΤΣ_ΚΤΕΛ->next = ΓΕΦΥΡΑ;
    // must fill in data for ΓΕΦΥΡΑ also
    ΓΕΦΥΡΑ->data = rand() 1;
    ΓΕΦΥΡΑ->next = NULL;

    // passing in ΤΣ_ΚΤΕΛ will print both structures now
    printList(ΤΣ_ΚΤΕΛ);
 
    return 0;
}

Demonstration.

Also see:

How to generate a random int in C?

Do I cast the result of malloc?

  • Related