c#do-while循环不能正常工作,因为我需要它

时间:2016-10-02 18:49:44

标签: c#

我希望我的循环重复,只要宽度小于0.5(MIN_WIDTH)或大于5.0(MAX_WIDTH),两者都被创建为常量双精度。 当我写数字0时,它会重复它应该重复,但如果我在0.1 - 0.4之间写任何东西它会跳过循环,为什么?

  do
        {
            Console.Write("Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + " :");
            widthString = Console.ReadLine();
            width = double.Parse(widthString);
        } while (width < MIN_WIDTH || width > MAX_WIDTH);

1 个答案:

答案 0 :(得分:3)

您似乎遇到了十进制分隔符的问题:如果在您当前的文化中(例如俄语RU-ru.(不是十进制)它忽略的分隔符,你会得到0.4 - &gt; 04 - &gt; {em}传递条件的4

补救措施:明确指定CultureInfo.InvariantCulture

do {
  Console.Write($"Give the width of the window between {MIN_WIDTH} and {MAX_WIDTH}: ");
  widthString = Console.ReadLine();

  double width;

  if (!double.TryParse(widthString, 
                       NumberStyles.Any, 
                       CultureInfo.InvariantCulture, 
                       out width))
    continue;
} while (width < MIN_WIDTH || width > MAX_WIDTH);