Question:

Uhm. Some help with the C++ random number generator.?

by  |  earlier

0 LIKES UnLike

Hi there, I just need abit of troubleshooting for this code.

#include <cstdlib>

#include <ctime>

#include <iostream>

int main()

{

srand((unsigned)time(0));

int random_integer;

for(int index=0; index<20; index++){

random_integer = (rand()%10)+1;

cout << random_integer << endl;

}

}

Can I ask what's wrong with this code, people?

It keeps telling me that cout and endl are undeclared

indentifiers, which doesn't make sense to me :(

 Tags:

   Report

2 ANSWERS


  1. instead you can try &quot; cout&lt;&lt;rand(); &quot;

    #include &lt;cstdlib&gt;

    #include &lt;ctime&gt;

    #include &lt;iostream&gt;

    int main()

    {

    cout&lt;&lt;rand();

    }


  2. OK

    your program is almost good. but if you want cout and endl  to work you need to say std::cout instead of just cout.

    an easier way to do it is to just go a line above the start of your main function and add using namespace std;

    but thats not it. you need to have a return value for your main function. just before the end of the main function add return 0; and your program should work.

    then there might be another problem. depending on the compiler you are using, you might just see a flash of a console. in order to make the console stay so you can read your random numbers, you need to add a statement like this just before your return statement.

    char f;

    cin&gt;&gt;f ; (if you chose to write using namespace std; on top of the program, or else you should say std::cin&gt;&gt;f)

    at the end your program should look like this:

    #include &lt;cstdlib&gt;

    #include &lt;ctime&gt;

    #include &lt;iostream&gt;

    using namespace std;

    int main()

    {

    srand((unsigned)time(0));

    int random_integer;

    for(int index=0; index&lt;20; index++){

    random_integer = (rand()%10)+1;

    cout &lt;&lt; random_integer &lt;&lt; endl;

    }

    char f ;

    cin&gt;&gt;f ;

    return 0;

    }

    I hope that didnt confuse you.

    good luck

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.