简体   繁体   English

在C#中访问数组元素

[英]Accessing array elements in C#

I am having trouble with writing code that takes a user inputted integer and uses that integer to access that element in the array and gets the sum of the element that the user inputted and the one before and after. 我在编写代码时遇到麻烦,该代码接受用户输入的整数,并使用该整数访问数组中的该元素,并获取用户输入的元素与之前和之后的元素之和。 For example, if a user inputs 1 I would want to have the element 0+1+2. 例如,如果用户输入1,则我希望具有元素0 + 1 + 2。 Please let me know if this information isn't enough and I will try to elaborate more. 如果此信息还不够,请告诉我,我将尝试详细说明。

Edit: To add more information, this is the code I have got done already and haven't had any problems with. 编辑:要添加更多信息,这是我已经完成的代码,并且没有任何问题。 The problem I am having is coming up with code that will be efficient in completing the task of adding the indexes from the user input. 我遇到的问题是提出了可以有效完成从用户输入添加索引的任务的代码。 Another example, if the user inputs 8 I would like the program to add the indexes 7+8+9, the number below the user input, user input and above. 另一个示例,如果用户输入8,我希望程序添加索引7 + 8 + 9,即用户输入下方的数字,用户输入上方的数字。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project
{
    class Program
{
    static void Main(string[] args)
    {
        int user;
        int[] numbers = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 };
        Console.Write("Enter a number from 1 to 8:");
        user = Convert.ToInt32(Console.ReadLine());
        if (user > 8 || user < 1)
        {
            Console.WriteLine("Please enter a valid number.");
        }
        for(int sum)
    }
}
}

Well, the sum would be: 好吧,总和是:

int sum = numbers[user - 1] + numbers[user] + numbers[user+1];

Does that answer your question? 这是否回答你的问题?


EDIT You started to write for (int sum) which doesn't really make sense. 编辑您开始for (int sum)编写代码for (int sum)这实际上没有任何意义。 The most efficient way is the above, but you can do it with a loop, too: 最有效的方法是上面的方法,但是您也可以循环执行此操作:

int sum = 0;
for (int idx = -1; i < 2; i++)
    sum = numbers[user + idx];

However, that's much harder to understand than the above... 但是,这比上面更难理解...


EDIT 2 I don't know if the array you provided is the real array you use, but in that case, the answer is even easier: 编辑2我不知道您提供的数组是否是您使用的真实数组,但是在这种情况下,答案甚至更简单:

sum = numbers[user] * 3;

:-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM