Random numbers?

Whenever I run the program that I am creating, a Calculator for the game "RISK" it compiles fine but when i enter the values to test it, I get numbers that i though would be outside the random number generators parameters. These numbers are the same every time though. I also tried to create a block of code to sort the number from highest to lowest. Here's what i used to generate random numbers :
#include <iostream>
#include <ctime>
#include <cstdlib>


1
2
3
4
5
6
7
   srand((unsigned)time(0));
   
int aone = rand() % 6 + 1;
   int atwo = rand() % 6 + 1;
   int athree = rand() % 6 + 1;
   int afour = rand() % 6 + 1;
   int afive = rand() % 6 + 1;


that is supposed to create 5 random numbers between 1 and 6

Here is the code for sorting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if ( aone > ahighone > ahightwo > ahighthree> ahighfour > ahighfive){
     ahighone = aone;
     }
if ( ahighone > aone > ahightwo > ahighthree > ahighfour > ahighfive){
     ahightwo = aone;
     }
if ( ahighone> ahightwo > aone > ahighthree> ahighfour > ahighfive){
     ahighthree = aone;
     }
if ( ahighone> ahightwo > ahighthree> aone > ahighfour > ahighfive){
     ahighfour = aone;
     }
if ( ahighone> ahightwo > ahighthree> ahighfour > aone > ahighfive){
     ahighfive = aone;
     }


I'm sure that this is where the problem is and also it is terribly inefficient. Is there some function to sort with?
Thanks in advance, super coders.
use a vector, and the sort function.
like this:
sort(v.begin(),v.end());
Last edited on
how would I use a vector?
Well a vector is like a dynamic array you'll need the #include <vector> header

1
2
3
4
5
6
vector<int>randomnumber; // this creates an empty vector
for (int i=0;i<5;i++)
{
randomnumber.push_back(rand()%6+1); // this adds a new element to the end of the vector which is the random number between 1 to 6
cout << randomnumber[i]<<endl; // this is just for checking if it's actually right.
} 

here try this code

Last edited on
if you know how many elements you need
you could use reserve to allocate the space for the vector
it would reduce the change of reallocating
Topic archived. No new replies allowed.