无法使用while循环中的值

问题描述 投票:-2回答:1

我想验证是否输入数字,然后验证数字是否在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;
}
c# validation variables console-application
1个回答
0
投票

首先:看一下: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()中的高斯总和用于求和。

还可以查看类和对象变量。

© www.soinside.com 2019 - 2024. All rights reserved.