vendredi 17 février 2017

generating four digits by using the C++ randint

here's the header file that I use while studying Stroustrup's book "Programming: Principles and Practice using C++":std_lib_facilities.h and I'm in the early chapters. In the exercise 13 of chapter 5 I got familiar with randint() function for making my "Cows and Bulls" game(the previous exercise) a bit more interesting, but when I use this function, it sometimes produces more digits than the number of times I iterate my loop. Here's the code:

vector<int> answer;
            for (int i = 0; i<4; ++i) { 
                int answer_digit=randint(10);
                answer.push_back(answer_digit); 
            }
            for (int i = 0; i < 4; ++i) std::cout << answer[i];
            _getch();
            std::cout << std::endl;

for instance in my case it gives 63109 for the first number, and then 4706 , then 5423 and then 7 more four-digit numbers and then again a five-digit one which is 94410. Why is that happening? Is that an error from the function in the library or it's just a silly mistake in my own code? Thanks.

(I know I could get a more realistic random by using a seed, but that's not related to my question(at least, my guess!)).




Aucun commentaire:

Enregistrer un commentaire