简体   繁体   English

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

[英]create method number generator in c# by parameter

I tried to Create a method to get value from the user then make a number generator of those values as a parameter but I Did not knew how ! 我试图创建一个方法来从用户获取值,然后将这些值的数字生成器作为参数,但我不知道如何!

 //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++;
  }

You could try: 你可以尝试:

// 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);

}

You can add in the end of your script: 您可以在脚本的末尾添加:

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

of course you should declare ran and to as int. 当然你应该声明ranto int。

edit:This is my whole project code: 编辑:这是我的整个项目代码:

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));
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM