You are here:

C++/a problem with rand() function



i have a question about rand() function,i know that rand() function is a function that choose numbers in a random way but why in this code below it just choose a same number everytimes i compile it?


I don't see the code below, but I think what it is every time a program starts the sequence of pseudo-random numbers returned by rand start at the same point.  Use srand to seed the random number.  I always use srand with a parameter like clock() to ensure the sequence is always random.

Tip: Sometimes to debug a program it's good to see the same input when using rand(), so there is some benefit to having the same sequence on each run of the program.

If I missed the point, please post the code.



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2017 All rights reserved.