在c#by参数中创建方法编号生成器

时间:2014-03-30 09:57:35

标签: c#

我尝试创建一个方法来从用户获取值,然后将这些值的数字生成器作为参数,但我不知道如何!

 //create a method that genereted the number of taple game
  public void zahra() 
  {
        Console.WriteLine("please enter value to random them betwen ");
        Console.Write("from ");
        ran    = Convert.ToInt32(Console.ReadLine());
        Console.Write("\n to ");
        to = Convert.ToInt32(Console.ReadLine());
        to++;
  }

2 个答案:

答案 0 :(得分:2)

你可以尝试:

// declare random instance outside of the method 
// because we don't want duplicate numbers
static Random rnd = new Random();

public static int GenerateRandomNumber()
{
    // declare variables to store range of number
    int from, to;

    // use while(true) and force user to enter valid numbers
    while(true)
    {
        // we use TryParse in order to avoid FormatException and validate the input
        bool a = int.TryParse(Console.ReadLine(), out from);
        bool b = int.TryParse(Console.ReadLine(), out to);

        // check values and ensure that 'to' is greater than 'from'
        // otherwise we will get a ArgumentOutOfRangeException on rnd.Next

        if(a && b && from < to) break; // if condition satisfies break the loop

        // otherwise display a message and ask for input again
        else Console.WriteLine("You have entered invalid numbers, please try again.");
    }

    // generate a random number and return it
    return rnd.Next(from, to + 1);

}

答案 1 :(得分:0)

您可以在脚本的末尾添加:

 Random r=new Random();
 Console.WriteLine(r.Next(ran, to));

当然,您应该将ranto声明为int。

编辑:这是我的整个项目代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RND
{
class Program
{
    static void Main(string[] args)
    {
        zahra();
    }
    public static void zahra()
    {
        Console.WriteLine("please enter value to random them betwen ");
        Console.Write("from ");
        int ran = Convert.ToInt32(Console.ReadLine());
        Console.Write("\n to ");
        int to = Convert.ToInt32(Console.ReadLine());
        to++;

        Random r=new Random();
        Console.WriteLine(r.Next(ran, to));
    }
}
}