Patrik Blå
Patrik Blå

Reputation: 79

c++ random number (Visual studio form)

I'm new to C++ (used to code C#) and I just cannot figure out how to create a random number in a Visual studio c++ forms environment. This is the code I use:

int randNumber;
srand(time(NULL));
randNumber = rand();
MessageBox::Show(randNumber.ToString());

I just put that code into form_load block.

The error message I get is:

error C3861: 'time': identifier not found

error C3861: 'rand': identifier not found

EDIT :

I did put the includes in my Form1.h file like this:

#pragma once

#include <cstdlib>
#include <ctime>

namespace Srand {

That seems to work, however the random numbers are very strange.

3100 3130 3146 3169 3192 3208 3231 3250 3270 3286

doesn't seem random at all, just randomly bigger.

Upvotes: 0

Views: 4306

Answers (3)

fatihk
fatihk

Reputation: 7919

Because your numbers are time dependent, you get very close results. You can try to randomize your number by applying some transformation to time() like firstly multiplying by a very big number then taking mod with respect to some big prime number.

Upvotes: 0

Asha
Asha

Reputation: 11232

You need to #include <cstdlib> and #include <ctime>.

Upvotes: 0

bash.d
bash.d

Reputation: 13207

You must include the corresponding headers like

#include <ctime> /* for time */

and

#include <cstdlib> /* for rand */

See here for rand and here for time.

Upvotes: 1

Related Questions