询问用户数组内的起始点和停止点

本文关键字:用户 用户数 数组 | 更新日期: 2023-09-27 18:15:27

在c#中,我如何要求用户在数组内开始和停止点?

下面是我目前为止的代码:
class Program
{
    static void Main(string[] args)
    {
        double[] num = { 10, 20, 30, 40, 50 };
        double n = num.Length;
        Console.Write("Elements of, arrary are:" + Environment.NewLine);
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine(num[i]);
        }
        double sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum = sum + num[i];
        }
        Console.WriteLine("The sum of elements:" + sum);
        Console.ReadKey();
    }
}

询问用户数组内的起始点和停止点

我猜您将取起始点和停止点之间元素的总和。从用户处获取两个输入,并将它们分配给for-loop的起始点和结束点。如:

 int startingPoint = Convert.ToInt32(Console.ReadLine());
 int endingPoint = Convert.ToInt32(Console.ReadLine());
 for(int i = startingPoint; i <= endingPoint; i++)
 {
      //take sum etc.
 }

不要忘记告诉用户数组中的元素值,以及他们正在输入的输入值。

另一个重要的事情是控制输入。它们应该是数字,并且在0-n之间,起点应该小于终点。

对于数字控件,可以这样写:

if (int.TryParse(n, out startingPoint))
{
     // operate here
} 
else
{
     Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}

startingPoint应介于0-n之间,不能为n。要控制它:

if (startingPoint >= 0 && startingPoint < n)
{
     // operate here
} 
else
{
     Console.WriteLine("Please enter a number between 0 and " + n + ".");
}

成功服用startingPoint后,你应该控制endingPoint。它应该在startingPoint-n之间。在控制为数字之后,你可以这样写:

if (endingPoint >= startingPoint && endingPoint < n)
{
     // operate here
} 
else
{
     Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
对于这个问题,我不知道我还能解释些什么。

如果您想提示用户开始和结束索引:

Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();