It is not always necessary to fill the numericalone-dimensional and two-dimensional arrays serial numbers or specific values. Perhaps, you will need to fill the elements of the array with random numbers. In C ++, there are special fynktsii rand() and srand().
They are in bibliotechnom file cstdlib, so that their use in the program, you need to connect this library file: #include <cstdlib> or #include <stdlib.h> (for older compilers).
If we use only functionrand() – will receive the same “random numbers” from run to run. Enter the following code and compile the program several times. Note, what “random numbers” there will always be the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <iostream> #include <cstdlib> // содержит srand() и rand() using namespace std; int main() { int randomDigits[3] = {}; for (int i = 0; i < 3; i++) { randomDigits[i] = rand(); // запись случайного числа, которое вернет rand() cout << randomDigits[i] << endl; } return 0; } |
A random number is generated in a string 11 and recorded in i-th element of the arrayrandomDigits. In the next string, ask him to show. Starting the program will see each time Only overnight and same numbers:
It turns out, that the numbers are generated is not entirely random. In order to achieve “present” random number at restartx program, you must apply the function srand() to function rand(). Thus it is necessary to pass it as a parameter function time() with a parameter NULL: srand(time(NULL)); (parameter or function argument – It `s that, that is written in the parentheses after the function name. When we consider the theme Functions in C ++, talk about this more in detail). In this way srand() It receives as a parameter the current system time, which will be different for each program starting. This will function rand() each time it is to generate random numbers. For use time() you must connect the library file ctime (time.h for older compilers): #include <ctime> .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> #include <cstdlib> #include <ctime> // содержит time() using namespace std; int main() { int randomDigits[3] = {}; srand(time(NULL)); for (int i = 0; i < 3; i++) { randomDigits[i] = rand(); cout << randomDigits[i] << endl; } return 0; } |
Try to run. You make sure, now generated different number at each compilation. I have turned this result:
All looks good. Only there is one point: range of random numbers, that are generated in such a way – from 0 to32767. You may need to fill in an array of numbers 200 to 300, from 0.1 to 1, from -20 to 20. This random number generation is possible and easy to implement. Let's look at a few example cases:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { setlocale(LC_ALL, "rus"); int randomDigits[10] {}; int randomDigits_2[10] {}; int randomDigits_3[10] {}; int randomDigits_4[10] {}; float randomDigits_5[10] {}; // для чисел c плавающей точкой srand(time(NULL)); for (int i = 0; i < 10; i++) { randomDigits[i] = rand() % 7; // 0 ... 6 randomDigits_2[i] = 1 + rand() % 7; // 1 ... 7 randomDigits_3[i] = 200 + rand() % 101; // 200 ... 300 randomDigits_4[i] = rand() % 41 - 20; // -20 ... 20 randomDigits_5[i] = 0.01 * (rand() % 101);// 0.01 ... 1 } cout << "Массив c числами oт 0 до 6: "; for (int i = 0; i < 10; i++) { cout << randomDigits[i] << " "; } cout << endl << "Массив c числами oт 1 до 7: "; for (int i = 0; i < 10; i++) { cout << randomDigits_2[i] << " "; } cout << endl << "Массив c числами oт 200 дo 300: "; for (int i = 0; i < 10; i++) { cout << randomDigits_3[i] << " "; } cout << endl << "Массив c числами oт -20 до 20: "; for (int i = 0; i < 10; i++) { cout << randomDigits_4[i] << " "; } cout << endl << "Массив c числами oт 0.01 дo 1: "; for (int i = 0; i < 10; i++) { cout << randomDigits_5[i] << " "; } cout << endl; return 0; } |
In the first the for loop random number generation happens certain ranges and their entry in the appropriate arrays. In each step of the cycle will generate new random numbers. Perhaps someone is difficult to understand how it happens. Let us consider in detail:
rand() % 7 – rand() it generates a number of further evaluated remainder of the division at 7 of that number. Clear, it may be of only From 0 to 6. For example generated 50 – the remainder of the division by 7 is equal to 1, generated 49 – the remainder of the division by 7 is equal to 0.
1 + rand() % 7 – very similar to the previous case, only 0 we will not see, and here 7 It will be in the range. eg generated 49 – the remainder of the division by 7 is 0 and adds one to it, generated 6 – the remainder of the division by 7 is 6 and again added unit.
200 + rand() % 101 – give us a number from 200 to 300. For example generated 100 – the remainder of the division by 101 is 100 and added 200. We get the number of 300. Is generated 202: 200 + (202 % 101)= 200 + 0 = 200.
rand() % 41 - 20 – from the – 20 to 20. For example generated 1: (1 % 40) – 20 = 1 – 20 = -19; generated 30: 30 – 20 = 10.
0.01 * (rand() % 101) – from the 0.01 to 1. For example generated 55: 0.01* 55 = 0.55.
Result:
To practice, try to solve the problem: a computer“thinks of” number from 1 to 7, a user has to guess it. If it does not work out – see our variant solutions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { setlocale(LC_ALL, "rus"); int randomDigit = 0; int version = 0; srand(time(NULL)); randomDigit = 1 + rand() % 7; cout << "Отгадайте число, которое я загадал (1-7):"; cin >> version; if (version == randomDigit) { cout << "Дa! Я загадал число - " << randomDigit << endl; } else { cout << "Нет! Я загадал число - " << randomDigit << endl; } return 0; } |
Tasks with rand() there is an article Tasks: Arrays in C++. Take some time and watch the video:
And you can do even more interesting: add a couple of conditions and will play “More less”
at:
setlocale(LC_ALL, “rus”);
int answer = 0;
int secretNumber = 0;
srand(time(NULL));
secretNumber = 1 + rand() % 10;
cout <> answer;
if (answer == secretNumber) cout << "Вы угадали! This number – " << secretNumber < secretNumber) cout << "Не верно! Unknown number is less than the entered you" << endl;
else if (answer < secretNumber) cout << "Не верно! Unknown number more than the entered you" << endl;
}
return 0;
int main(int argc, char** argv) {
setlocale(LC_ALL,”rus”);
srand(time(0));
cout<<"Ïðèâåò äðóæîê ïèðîæîê! Äàâàé ÿ ÷ çàãàäàþ Enei [0;100]\OU Na ioaaaaaou?\n(Îòâåòü ok/no)"<<endl;
char answer[3] = "";
cin.getline(answer,3);
char answers[2][3]{"no","ok"};
bool whil = true;
if(strcmp(answer,answers[1])==0){
int RANDOM = 0 + rand() % 101;
int Person = 0;
int p = 0;
cout<<"Îòëè÷íî!\nIdaaeiaeeoa naith oeodo: "<>Person;
if(Person>RANDOM){
cout<<"Ìîÿ öèôðà ìåíüøå"<<endl;
P++;
}
if(Person<RANDOM){
cout<<"Ìîÿ öèôðà áîëüøå"<<endl;
P++;
}
if(Person==RANDOM){
P++;
cout<<"Ïîçäðàâëÿþ! Âû óãàäàëè ìîþ öèôðó çà "<<P<<" ïîïûòîê "<<endl;
whil = false;
cout<<"Íó ëàäíî, Ïîêà!"<<endl;
}
}
}
else if(strcmp(answer,answers[0])==0){
cout<<"Íó ëàäíî, Ïîêà!"<<endl;
}
return 0;
}
or
The most washed-site throughout the galaxy
Perhaps, I realized something right, but third example 23 ribbon
randomDigits_5[i] = 0.01 * (rand() % 101);
// 0.01 … 1
Is it not from 0 to 1. Rand may also be equal 101, 202, 303, 0 , etc.. d.?
No he can't. 101 this is the limit (not inclusive) to which the number will be generated. That is, whatever number you substitute after % it will not be generated, and the maximum will always be on 1 Less (bo rand() generates integer values).
randomDigits_5[i] = 0.01 * (rand() % 101);// 0.01 … 1
then I think the mistake a little,i.e.
0.01*100= 1 , but not 0.01
oops, I forgot about 0 , rather
0.01*0=0
Thank you to your site for existence!
I'm preparing for the exam in C ++ on your content.
I study in the Moscow Engineering Physics Institute))) Now the terrible task not cause such fear, like before, interesting, I would say.
Many thanks!