1
votes

I'm new to programming and I'm trying to build a die roller game in C#.

The program asks the user for the number of sides and then rolls a dice with a random number.

I have the following pseudocode:

  1. ask user for the number of sides.
  2. roll the die with a random number with max range being the number of sides.
  3. tell the user the number rolled

My question is how do I roll the dice with generating a random number in range specified by the user?

5
What you're basically asking is how do you get a random number within a certain range. Look into the Random class. - Jon B

5 Answers

2
votes

The System.Random class is commonly used to generate casual random numbers.

It has an overload of a method called Next which generates a random integer that is greater than or equal to 0 and strictly less than the passed integer argument.

Thus if the user chooses an n-sided die, and you have an instance of Random r,

r.Next(n) + 1

will generate a random integer between 1 and n inclusive.

It is good practice to create a single instance of Random and reuse it, because if you create several instances close together they will all generate the same numbers.

1
votes
Random random = new Random();
int randomNumber = random.Next(1, userInput);

One thing for you to know though is the random function isn't exactly random, its random but in the same random order everytime.. I'll let you look on your favourite search engine for seeding ;)

0
votes

To get a Random integer between 0 and 100 with 100 not included:

Random random = new Random();
int randomNumber = random.Next(0, 100);
0
votes

System.Random, specifically System.Random.Next(Int32, Int32) should get you started.

Random.Next(Int32, Int32)
Returns a random number within a specified range.
0
votes
public int RollDice(int iNoSides)
{
  var rand = new Random();
  return rand.Next(iNoSides) + 1
}

A simple google of random number c# would of got you more or less this exact code.

EDIT

You have the link to the MSDN documentation from other answers and comments, I know your new to programming but the best way to learn is to try as hard as you can to get something. If you get to a state where your mind can't function any more, posting your attempt with your question on Stack will make people generally a lot happier that they are genuinely helping somebody that is stuck

EDIT 2

Following @Rawling's comment, I realised that the overload of the method states that Next(n) returns a Non-negative number less than the specified maximum.