错误的随机数 C

Wrong Random Numbers C

我正在构建一个程序来模拟一辆公共汽车经过公共汽车站并搭载随机数量的乘客 (0-15) 问题是当我尝试打印上车的乘客数量时公共汽车站我得到很多大于 15 的数字。

这是我的程序的一部分:

#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()%15+1;
    ΤΣ_ΚΤΕΛ->next = ΓΕΦΥΡΑ;

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

下面有一些调整可以解决您的基本问题,并在评论中进行解释:

#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()%15+1;
    ΤΣ_ΚΤΕΛ->next = ΓΕΦΥΡΑ;
    // must fill in data for ΓΕΦΥΡΑ also
    ΓΕΦΥΡΑ->data = rand()%15+1;
    ΓΕΦΥΡΑ->next = NULL;

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

Demonstration.

另见:

How to generate a random int in C?

Do I cast the result of malloc?