Need help with getting random numbers in c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Need help with getting random numbers in c++

There is a function for getting random numbers in c++ but i dont know what that is. I need to make a sudoku and need help with a random number input.

12th Jan 2017, 6:15 AM
prabin
prabin - avatar
7 Answers
+ 7
#include<iostream> #include<cstdlib>// c standard library #include <ctime> using namespace std: int main() { srand(static_cast<unsigned int>(time(NULL))); //then call rand func cout<<rand(); return 0; }
12th Jan 2017, 7:01 PM
hindstrust
+ 5
You could use srand. As far as I know, you can't generate numbers that are 100% random in C++. Instead, we could use the current time to help us generate what would look to us like a random number. For this, you will need to include the ctime library. srand seeds the pseudo-random number generator used by rand() with the value seed. If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with the same seed, it must produce the same sequence of values. #include <cstdlib> #include <iostream> #include <ctime> using namespace std; int main() { srand(time(0)); //use current time as seed for random generator cout << rand() << endl; //generate number }
12th Jan 2017, 6:56 AM
Daniel Stanciu
Daniel Stanciu - avatar
+ 4
see rand()
12th Jan 2017, 6:44 AM
jay
jay - avatar
+ 2
you can put some answers here together for the code, but if you ever have a question on the c (or c++) library and their functions just google "c++ <name>" and click on the first link. to answer your question: (i guess you mean rand () ) rand () does not generate random numbers, it generate a fixed sequence on whatever is initialized with srand. fun fact: those are, as said before, pseudo-random integers. you actually CAN create random numbers,, but thats mostly too much work for those simple things. use rand, srand etc. and read through the <random> header.
12th Jan 2017, 8:03 PM
Abraham Soeyler
Abraham Soeyler - avatar
+ 1
You can use a more modern random number generator instead of the old c style "rand ()" Look into random_device default_random_engine and uniform _int_distribution <int>
12th Jan 2017, 6:55 AM
Blood
Blood - avatar
+ 1
try the rand() function as others already shown...but by default the ranges are not fixed..so to fix the ranges try this.. c = rand(0,10); or something similer depending your needs
12th Jan 2017, 9:06 PM
ARNAB BISWAS
ARNAB BISWAS - avatar
0
you can use the rand () function : Do use the cstdlib header //This program generates random numbers #include <iostream> #include <cstdlib> int main () { int y ; y = rand () ; cout << y ; return 0 ; }
12th Jan 2017, 11:08 AM
Hammer Andrew
Hammer Andrew - avatar