• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

Simple C++ queston...

Stormin

n00b
Joined
Jul 11, 2004
Messages
51
I forgot how to generate random variables in C++. I think it is the rand() function but it doesnt seem to work. I need to produce a random number between 1 and 100. Can anyone help me? thanks.
 
If i recall correctly (and I may not...) The rand() function is defined as a random number between 0 and 1....

Consider some multiplication.....

i.e.: result of rand x 100 = a number 1-100 (round it if you please)
 
Code:
#include <cstdlib>
#include <ctime>
#include <iostream>

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

      std::cout << rand() % 100 + 1 << std::endl;

      return 0;
}

rand will generate numbers other than 0 and 1, so "rand() % 100 + 1" will generate a number between 1 and 100.

srand() is used so that the random generator uses a different seed every time the program is run.
 
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>

#define MAX 100
#define MIN 1
using namespace std;

int main (void)
{
	srand( time(NULL) );
	cout	<< rand() % (MAX + 1 - MIN) + MIN;

	return 0;
}

Pretty sure thats being scaled right, might want to check ranges. Anyway, srand sets the random seed to the current time (represented in seconds since 1970). (This ensures your random numbers dont repeat in order everytime you start the program) rand() returns a random int in the range of 0 to (2^15)-1. The mod function scales it down to the wanted range and then adds your min.

You may want to clean that up looks ugly to me, (Like find MAX+1-MIN and hardcode it in)

Looks like I took too long posting =)
 
Back
Top