rand() returns a random number out of a very large range. % is the modulus operator which gets you the integer remainder of what's on the left side when divided by what is on the right side. If you divide a number by 6, the possible remainders are going to be 0, 1, 2, 3, 4, 5. So a large random number % 6 will be a random number between 0 and 5. Add 1, and you have a number from 1 to 6.
1 2 3 4 5
|
int main() {
srand(time(0));
int random_number_between_1_and_6 = rand() % 6 + 1;
....
}
|
Also the below doesn't make sense to do.
1 2 3 4
|
using namespace std;
using std::cout;
using std::cin;
using std::endl;
|
using namespace std; makes the whole std namespace visible, including std::cout, std::cin, and std::endl. It's good practice to not use the using directive because in larger projects it could lead to naming conflicts. Instead you would just put std:: before each use of cout, cin, endl, etc. But if not, then it is at least better practice to do this
1 2 3
|
using std::cout;
using std::cin;
using std::endl;
|
instead of this
using namespace std;
because you now only are risking naming conflicts with the names cout cin and endl, which are unlikely to arise.
Also remember for future reference to never use the using directive in header files, only implementation files (.c, cpp).