Debugging Random Function in C: Generates Only "3

  • Thread starter Thread starter sandy.bridge
  • Start date Start date
  • Tags Tags
    Function Random
Click For Summary
SUMMARY

The discussion focuses on debugging a C function that generates random numbers using the rand() function. The primary issue identified is the failure to initialize the random number generator with srand(), which must be called once in the main() function to ensure varied outputs. The participants also highlight that calling srand() multiple times within a loop leads to repeated values. A corrected version of the function is provided, demonstrating proper initialization and usage of random number generation.

PREREQUISITES
  • Understanding of C programming syntax and structure
  • Familiarity with the rand() and srand() functions
  • Knowledge of pseudo-random number generation concepts
  • Basic understanding of control flow with loops and conditionals in C
NEXT STEPS
  • Learn about the differences between pseudo-random and true random number generation
  • Explore the use of time() for seeding random number generators
  • Investigate alternative random number generation libraries in C, such as random() from cstdlib
  • Study best practices for generating random numbers in competitive programming and simulations
USEFUL FOR

C programmers, software developers working with random number generation, and anyone interested in debugging C code related to random functions.

  • #31
sandy.bridge said:
It seems that it isn't returning the ith repeat.

You should still remove the first call to random(k) in your main() function.
It obfuscates the results.
 
Technology news on Phys.org
  • #32
Thanks! I had that out before but I must have opened the wrong one. Eventually I will get this random function down pat!
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
3
Views
2K
Replies
11
Views
2K
Replies
22
Views
5K
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K