random number help

hi guys!
i need to generate a random number which must be between 3 and 10 and it must be an even number;
is there any code you help me with?
thanks by the way.

so your choices are 4, 6, 8 and 10 - stick these numbers into std::vector<int>, std::shuffle this vector and select v[0] - http://en.cppreference.com/w/cpp/algorithm/random_shuffle
i am a begineer programmer,i cant understand.
if i get a situation like i must ramdomly choose odd numbers between 0 and 32767;
is there any easy method
generate a random number which must be between 3 and 10 and it must be an even number

Rather limits the choice.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
   srand( time( 0 ) );
   int a[] = { 4, 6, 8, 10 };
   cout << a[ rand() % 4 ];
}
thanks!
and if it is between 0 and 32767, i cant type all even numbers into array!
ha! i knew you'd come back with that. in that case you'd run the random number generator until an even number came up
ahhh? i cant understand..
and if it is between 0 and 32767, i cant type all even numbers into array!
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
   srand( time( 0 ) );
   cout << 2 * ( rand() % 16384 );
}
Last edited on
what is use of line 7?
what is use of line 7?


To "seed" your random number generator; i.e. pick a pseudo-random starting point within the rand()-generated sequence.

Without it you will get the same "random" value every time - try it!

It's based on current time, on the assumption that students' waking hours are uniformly distributed throughout the day. Ahem.
Last edited on
thanks...
Try this:
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
#include <iostream>
#include <cstdlib>
#include <ctime>

int RandomEvenNumber(int min, int max)
{
  int num = -1; // some initial value
  do
  {
    num  = min + (rand() % ((max - min) + 1));
  }
  while(num % 2 != 0);

  return num;
}

int main()
{
  const int MIN = 3;
  const int MAX = 10;
    
  srand (time(0));
  
  for (int i = 0; i < 20; i++)
  {
    int num = RandomEvenNumber(MIN, MAX);
    std::cout << "Num = " << num << "\n"; 
  }
  system("pause");
  return 0;
}
what is std::cout?in line 27?
Instead of putting a blanket using namespace std; at the top of the program, you may choose to qualify functions individually with the name of the namespace, whether it's std:: or someothernamespace::
Topic archived. No new replies allowed.