正数验证C#

时间:2018-11-07 19:41:44

标签: c#

我正在尝试编写一种方法来检查数字是否为正,并且不断收到错误消息,提示“并非所有代码路径都返回一个值”,而且我不确定自己在做什么。

public static double IsValad(double x)
{
    Boolean loopValue = true;
    while (loopValue == true)
    {
        if (x > 0)
        {
            loopValue = false;
            return x;
        }
        else
        {
            Console.WriteLine("Error: Please enter a positive value.");
            x = double.Parse(Console.ReadLine());
           return x;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您不会在while循环之外返回任何值。取出while循环。没必要

public static double IsValid(double x)
{
    if (x > 0)
    {
        return x;
    }
    else
    {
        Console.WriteLine("Error: Please enter a positive value.");
        x = double.Parse(Console.ReadLine());
        return x;
    }
}

答案 1 :(得分:0)

如果您想循环播放直到用户理解正确,请考虑以下内容:

 public static double GetPositiveNumber()
 {
     while (true)
     {
         Console.Write("Enter a Positive number: ");
         var response = Console.ReadLine();
         if (!double.TryParse(response, out var doubleValue))
         {
             Console.WriteLine("You must enter a valid number");
             continue;     //causes control to jump to the end of the loop (and back again)
         }

         if (doubleValue > 0)
         {
             return doubleValue;     //The only exit to the loop
         }
         //if I get here, it's a valid number, but not positive
         Console.WriteLine("Sorry, the number must be positive...");
     }
 }