0

我将如何为此代码编写另一个名为 noNegatives 的函数?我想用另一个名为 noNegatives 的函数重写代码,但我仍然希望程序做同样的事情。

    class Program
    {
        static void Main(string[] args)
        {
            string numberIn;
            int numberOut;

            numberIn = Console.ReadLine();

            while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
            {
                Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
                numberIn = Console.ReadLine();
            }
        }       
    }
4

3 回答 3

0
static void Main(string[] args)
{
    int number = NoNegatives();
}
static int NoNegatives()
{
    int numberOut;

    string numberIn = Console.ReadLine();

    while (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
    {
        Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
        numberIn = Console.ReadLine();
    }
    return numberOut;
}
于 2013-10-05T13:02:48.637 回答
0

以下是您可以编写它的最简单的方法

static void Main(string[] args)
            {
                int retVal=0; 
                string numberIn;
                int numberOut;
                numberIn = Console.ReadLine();

                while(noNegatives(numberIn,numberOut)=0)
                {

                }
             } 

    int noNegatives(String numberIn,int numberOut)
    {


                numberIn = Console.ReadLine();

                if (!int.TryParse(numberIn, out numberOut) || numberOut < 0)
                {
                    Console.WriteLine("Invalid. Enter a number that's 0 or higher.");
                    return 0;

                }
                else
                {
                   return 1;
                }
    }
于 2013-10-05T12:52:50.453 回答
0

这个问题与此处发布的问题非常相似。

    static void Main(string[] args)
    {
        string numberIn = Console.ReadLine();
        int numberOut;

        while(!IsNumeric(numberIn))
        {
            Console.WriteLine("Invalid.  Enter a number that's 0 or higher.");
            numberIn = Console.ReadLine();
        }
        numberOut = int.Parse(numberIn);
    }

    private static bool IsNumeric(string num)
    {
        return num.ToCharArray().Where(x => !Char.IsDigit(x)).Count() == 0;
    }

由于负号不是数字,因此 IsNumeric 将返回 false 为负数。

于 2013-10-05T15:36:30.960 回答