c++ generation of random numbers

Asked 2 years ago, Updated 2 years ago, 72 views

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;
int main() {

 srand(time(0));

 int num = rand()%101;
 for(int i = 0; i <=9; i++){
   cout << num << endl;
 }
}

If I print it out, all 9 random numbers are the same, but how do I print out 10 different random numbers in the for statement?

c c++ random

2022-09-20 19:44

3 Answers

Try a lot of this and that before you ask questions. You have to go through that process to become a great programmer. It doesn't help you much in the long run to ask questions without worries and headings. Cheer up.

You must run the rand() function in the for loop to generate a new random number each time the for loop turns. Move the position of the rand() function.

Create an array in advance and store it in the array when random numbers are generated in course 1.

When the for loop in process 1 is repeated again and a new random number is generated, compare it with the numbers in the array in process 2, and if it is equal to any value in the array, do not put it in the array, but create a random number again and repeat the comparison with the numbers in the array.

Continue to repeat course 3.

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

bool check_dup(int array[], int cnt, int num);

int main() {
    constexpr int loop_num = 10;
    constexpr int max_num = 100;

    int num = 0;
    int nums[loop_num] = { 0, };
    int num_cnt = 0;

    srand((unsigned int)time(NULL));

    for (int i = 0; i < loop_num; ++i)
    {
        num = rand() % (max_num + 1);

        if (check_dup(nums, num_cnt, num))
        {
            --i;
            continue;
        }
        else
        {
            nums[num_cnt] = num;
            ++num_cnt;
        }
    }

    for (int i = 0; i < loop_num; ++i)
        cout << nums[i] << ' ';

    cout << '\n';

    return 0;
}

bool check_dup(int array[], int cnt, int num)
{
    bool result = false;

    for (int i = 0; i < cnt; ++i)
    {
        if (array[i] == num)
        {
            result = true;
            break;
        }
    }

    return result;
}


2022-09-20 19:44

How much do you think and ask questions? If you know what the for loop is and what the rand function does, it's a problem you can be done on its own.

If you ask a question because you don't know even though you've been thinking about it very hard, programming is not your aptitude. Do something else. Even if you're not good at programming, you can make a living.


2022-09-20 19:44

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;
int main() {

 srand(time(0));

//  int num = rand()%101; part of the problem.

 for(int i = 0; i <=9; i++){
//   cout << num << endl; part of the problem
    cout << rand()%101 << "\n";
 }
}


2022-09-20 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.