不能使用 while 循环之外的值

Cant use the value out of the while loop

我想验证他们是否输入数字,然后验证数字是否在 20 - 50 之间,然后计算之前所有正数的总和。

int i, sum = 0;

var valid = false;
while (!valid)
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("Please enter a number between 20 and 50(50 is included)");
    Console.WriteLine("Only Numbers will be accepted");
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");
    Console.ForegroundColor = ConsoleColor.Yellow;

    var val = Console.ReadLine();
    valid = !string.IsNullOrWhiteSpace(val) &&
        val.All(c => c >= '0' && c <= '9');
    Console.WriteLine(val + " is what you entered");
}

Int16 num = int.Parse(val);
if (num > 20 && num <= 50)
{
    for (i = 0; i <= num; i++)
    {
        sum = sum + i;
    }
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");

    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.WriteLine("Sum of all numbers before "+ Convert.ToString(num) + " is " + Convert.ToString(sum));

    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");
    Console.ForegroundColor = ConsoleColor.Green;
}
else
{

    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");

    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Number is not within the limits of 20-50!!!");

    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("---------------------");
    Console.ForegroundColor = ConsoleColor.Green;
}

首先:看一下这个:https://en.wikipedia.org/wiki/Gauss_sum求和。

其二:代码:

static void Main(string[] args)
        {
            var valid = false;

            while (!valid)
            {
                var line = Console.ReadLine();

                if(Int16.TryParse(line, out var numericValue))
                {
                    if(numericValue >= 20 && numericValue <= 50)
                    {
                        int sum = Calculate(numericValue);
                        valid = true;
                    }
                }
                else
                {
                    // It was not a number or outsinde the range of Int16
                }
            }
        }

        private static int Calculate(int num)
        {
            return (num * (num + 1) / 2);
        }

Int16.TryParse 轻柔地检查 Console.ReadLine() 中的值是否是 Int16 范围内的数字。我在 Calculate() 中使用高斯和求和。

另请查看 class 和对象变量。