Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I generate random int numbers within a set range (without duplicates!) within a class constructor?
    primarykey
    data
    text
    <p>I am self-learning C++ from a text book and I have a problem to solve, outlined below.</p> <p>I have the following class structure:</p> <pre><code> #include &lt;iostream&gt; #include &lt;cstdio&gt; #include &lt;ctime&gt; using namespace std; class classroom{ char name[25]; int student_id; float grades[10]; float average; int num_tests; float letter_grade; public: void enter_name_id(void); void enter_grade(void); void average_grades(void); void letter_grades(void); void output_name_id_grade(void); classroom(); }; </code></pre> <p>And I have the following Constructor for the above class:</p> <pre><code> classroom::classroom(){ int i; srand((unsigned)time(0)); int random_integer=0; random_integer = (rand()%5) + (rand()%5); num_tests=0; average=0.0; for(i=0;i&lt;10;i++){ grades[i]=0.0; } for(i=0;i&lt;27;i++){ name[i]='-'; } cout&lt;&lt;"\n*****************Finished*****************"; } </code></pre> <p>There will be 3 students of this class structure declared in the <code>main</code>:</p> <pre><code>int main() { classroom students[3]; //and so... } </code></pre> <p>I need to generate a unique student ID for each student in the constructor within a range of values, say, 0 to 10.</p> <p>I have copied the following code snippet into the constructor. It generates my random number for me within the desired range:</p> <pre><code>srand((unsigned)time(0)); int random_integer=0; random_integer = (rand()%5) + (rand()%5); </code></pre> <p>The problem is that I need to get rid of any duplicates within the range of random numbers that are generated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload