issue with c# Random

r ht 1 Reputation point
2022-01-17T05:25:00.603+00:00
using System;

namespace arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int items = 10;
            int[] test = new int[items];


            //write items random int
            for (int i = 0; i < items; i++)
            {
                test[i] = rand.Next(0,2); 
// should make test[i] range between 0 and 2 NOT 0 and 1?
// rand.Next(0,1); should include 1?
// dont get the logic in Random, could someone explain why this is not so

            }

            // output items arrays
            Console.WriteLine(test.Length);
            for (int t = 0; t < items; t++)
            {
                Console.Write("  t=" + t + "  test=");
                Console.WriteLine(test[t]);
            }
            Console.ReadLine();


        }

    }
}
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-01-17T06:31:42.517+00:00

    @r ht , if you want to make the member of the array between 0 and 2, please use test[i] = rand.Next(0,3);

    As the Microsoft doc said:

    The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue - 1. However, if maxValue equals minValue, the method returns minValue.

    You can find the sentence from the doc Random.Next Method.


    If the response is helpful, please click "Accept Answer" and upvote it.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Saga 431 Reputation points
    2022-02-10T22:31:05.317+00:00

    Hi, rand.Next doesn't work that way.

    If you want to get a number in the range of 0 to N, then use the following:

    rand.Next(N + 1)

    In your case, you want number from 0 to 2, so use the following
    //Get random number.
    Random rand = new Random();

    //2 + 1 = 3
    int iRnd = rand.Next(3).ToString();

    I should mention that .Next(3) is equivalent to .Next(0, 3) only when you want the minimum to be 0.

    Good luck! Saga

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.