QUESTION 1
In this line of code, I get that it's using the date/time to seed the code for a more random number each time, I'm just wondering what the < > operators are doing?

srand(static_cast<unsigned int>(time(0)));

I realize, they're making time into an unsigned int, but why not do this:

srand(unsigned int = time(0));

I realize my questions revolve around the < > but...yeah what are they doing exactly? Is static_cast a function? I've only ever seen functions like this:

function([I]value[/I])

not like this:

function<type>(value);

QUESTION 2

Just to see what would happen, I copied and pasted the code twice in an effort to see if the processor would duplicate dice rolls that run at the same second. Never tried it though - when I went to compile I got an error that said 'redeclaration of 'int randomNumber', and another error 'Redeclaration of int die. These int's aren't set to be constants so why can't I change them again in the same block of code?

ex:

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

using namespace std;

int main()
{
	//Roll 1
	srand(static_cast<unsigned int>(time(0))); //seed random number generator
	
	int randomNumber = rand();	//generate random number
	
	int die = (randomNumber % 6) + 1;	// get a number between 1 and 6
	cout << "You rolled a " << die << endl;
	
	//Roll 2
	srand(static_cast<unsigned int>(time(0))); //seed random number generator
	
	int randomNumber = rand();	//generate random number
	
	int die = (randomNumber % 6) + 1;	// get a number between 1 and 6
	cout << "You rolled a " << die << endl;
	
	return 0;
}

Errors were line 20, and 22.

Edited 5 Years Ago by crapgarden: n/a

Question #1. It's a C++ template, which is a powerful feature.
Question #2. You have two variables with the same name in the same scope. That's a no-no in every programming language I know of.

Q1
I haven't covered Templates yet, but that makes sense now.

Q2
I made it work. I was trying to 'declare' the variables twice instead of simply reassigning values. Still...that IS a no no - even if it works. Thanks!
*BTW - yes it generates the same number every time so far.

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

using namespace std;

int main()
{
	//Roll 1
	srand(static_cast<unsigned int>(time(0))); //seed random number generator
	
	int randomNumber = rand();	//generate random number
	
	int die = (randomNumber % 6) + 1;	// get a number between 1 and 6
	cout << "You rolled a " << die << endl;
		
	//Roll 2
	srand(static_cast<unsigned int>(time(0))); //seed random number generator
	
	randomNumber = rand();	//generate random number
	
	die = (randomNumber % 6) + 1;	// get a number between 1 and 6
	cout << "You rolled a " << die << endl;
	
	return 0;
}

Edited 5 Years Ago by crapgarden: n/a

Oh sorry, I didn't know you were calling srand() every time you wanted a new random number.

call srand() once for the life of the program.

This question has already been answered. Start a new discussion instead.