c++ - srand not initializing a new output every time -
this question has answer here:
- srand() — why call once? 6 answers
- c program - srand() [duplicate] 6 answers
- recommended way initialize srand? 13 answers
- problem getting multiple random numbers [duplicate] 1 answer
i'm creating program in need output different thing different time. random, outputs same thing, , yes put in srand.
void setcolor() { srand(time(null)); int col = rand() % 4 + 1; if (col == 1) { cout << "white "; } else if (col == 2) { cout << "brown "; } else if (col == 3) { cout << "black "; } else if (col == 4) { cout << "spotted "; } } int main() { (int = 0; <= 5; ++i) { setcolor(); } }
srand must called once , not in each loop.
void setcolor() { int col = rand() % 4 + 1; if (col == 1) { cout << "white "; } else if (col == 2) { cout << "brown "; } else if (col == 3) { cout << "black "; } else if (col == 4) { cout << "spotted "; } } int main() { srand(time(null)); (int = 0; <= 5; ++i) { setcolor(); } }
it works way because srand initialize "global variable" used rand() function.
time(null) return number of seconds elapsed 1st january 1970. using 5 times same value because of initialisation of "global variable".
however, in c++, not right way use random values. please prefer use random header instead (http://en.cppreference.com/w/cpp/numeric/random) :
#include <iostream> #include <string> #include <map> #include <random> int main() { std::random_device rd; std::map<int, int> hist; std::uniform_int_distribution<int> dist(0, 9); (int n = 0; n < 20000; ++n) { ++hist[dist(rd)]; // note: demo only: performance of many // implementations of random_device degrades sharply // once entropy pool exhausted. practical use // random_device used seed // prng such mt19937 } (auto p : hist) { std::cout << p.first << " : " << std::string(p.second/100, '*') << '\n'; } }
Comments
Post a Comment