'Wrong Random Numbers C
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()%15+1;
ΤΣ_ΚΤΕΛ->next = ΓΕΦΥΡΑ;
printList(ΓΕΦΥΡΑ);
return 0;
}
Solution 1:[1]
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()%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;
}
Also see:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yano |
