-3

Use a random number function to randomly generate 10 integers between 0 and 99 with 0 and 99 included

Wayne Grets
  • 1
  • 1
  • 3
  • 1
    Welcome to Stack Overflow! We are not here to make your homework if you don't show any research yourself. If, however, you show what you have tried yourself, e.g. by posting a [mcve] and listing the sites on the internet you've researched, we're glad to help you on the final meters. See https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions – akraf Nov 30 '18 at 08:57

1 Answers1

1

It's quite simple. You need to use standart srand/rand functions. Look at this example:

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

int main() 
{
    // initialize random generator, by current time
    // so that each time you run - you'll get different values
    std::srand(std::time(nullptr)); 

    for(int i=0;i<10;i++)
    {
        // get rand number: 0..RAND_MAX, for example 12345
        // so you need to reduce range to 0..99
        // this is done by taking the remainder of the division by 100:
        int r = std::rand() % 100;

        // output value on console:
        std::cout << r << std::endl;
    }
}

And this is the modern variant of realization, using c++11. Some people like it more:

#include <random>
#include <chrono>
#include <iostream>


int main()
{
    auto t = std::chrono::system_clock::now().time_since_epoch().count();
    std::minstd_rand gen(static_cast<unsigned int>(t));

    for(int i=0;i<10;i++)
        std::cout << gen() % 100 << std::endl;
}
snake_style
  • 1,139
  • 7
  • 16
  • Ok, my professor hasn't taught us any of this, all we've used before is #include and including a class. Is there any way to generate the random numbers another way? Besides the loop, I don't know what the other part of your code means. – Wayne Grets Nov 30 '18 at 08:43
  • You need to read some books, do not rely on professor only. I'll comment some code you to understand. – snake_style Nov 30 '18 at 08:50
  • Ok I researched a bit and I somewhat understand the srand part but in the video, I watched they used srand(time(0); what significance do does std:: have? and why nullptr? – Wayne Grets Nov 30 '18 at 09:18
  • std::time_t time( std::time_t* arg ). This function waits for a pointer, not int(0). Maybe, there is an "oldschool technic" in that video - based on that **#define NULL 0** or **#define NULL nullptr**. You, also, can write **std::srand(std::time(0));** or **std::srand(std::time(NULL));** – snake_style Nov 30 '18 at 09:51
  • This is very outdated code. – MSalters Nov 30 '18 at 10:20
  • @MSalters modern version added for you ))) – snake_style Nov 30 '18 at 16:57