检查并计算c#中当前索引键数组旁边的值
if (theArray[i-1] < theArray.Length && theArray[i-1] != null)
这是我经过一番研究后得到的。但它只给了我索引错误,因为我做了 i-1。
但我想要 if 语句检查 i-1 上的键/索引是否存在,然后做一些事情..
看看我想要做的是加上当前索引旁边的索引值。
for (int i = 0; i < theArray.Length; i++)
{
Left = 0;
Right = 0;
if (i != 0)
{
Left = theArray[i - 1];
}
if (theArray[i + 1] < theArray.Length)
{
Right = theArray[i + 1];
}
calc = Left + Right;
output2.Text += calc + ", ";
}
因此,如果左侧存在,则更改左侧值(默认为 0、右侧和左侧),如果右侧存在,则更改右侧值。然后计算从 theArray[] 中获取的两个值。
例如,如果它在 theArray[16] 上,则应该将左侧、theArray[15] 和 theArray[17] 相加。
if (theArray[i-1] < theArray.Length && theArray[i-1] != null)
Is what i got after some research. But it gives just gives me out of index error, because i do i-1.
But i want the if statement to check whether the key/index on i-1 exists, then do something..
See what i want to do is plus the values of the indexes next to the current index.
for (int i = 0; i < theArray.Length; i++)
{
Left = 0;
Right = 0;
if (i != 0)
{
Left = theArray[i - 1];
}
if (theArray[i + 1] < theArray.Length)
{
Right = theArray[i + 1];
}
calc = Left + Right;
output2.Text += calc + ", ";
}
So if the left is there then change the left value (default is 0, right and left), and if right is there then change the right value. And then calculate both values taken from theArray[].
E.g if its on theArray[16] it should take the left, theArray[15] and theArray[17] and plus together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您正在寻找:
或者可能:
我通常会在这样的循环中使用
i
:更新:
您不能使用
i-1
,因为在第一次迭代,当i == 0
时,其计算结果为-1
。这是数组中的非法索引。更新2:
我想我明白你现在想要做什么。这是一种方法:
I think you are looking for:
Or possibly:
I would normally be using
i
in a loop like this:Update:
You can't use
i-1
, because on the first iteration, wheni == 0
, this would evaluate to-1
. This is an illegal index in an array.Update 2:
I think I understand what you are trying to do now. Here is one way to do it:
要检查
i
是否是有效的数组索引,您可以执行以下操作:然而,这只在极少数边缘情况下才有必要,因此这样做更实际:
一旦您知道它是有效的索引,如果需要,您可以检查
null
。To check if
i
is a valid array index, you can do this:That will only be necessary in rare edge cases, however, so it's more practical to do this:
Once you know that it's a valid index, you can check for
null
if need be.您的问题是索引或具有给定索引的数组值是否存在?
对于数组,如果 0 <<,则始终可以确保索引 n“存在”。 n <数组.长度。
如果要检查数组值,请首先检查索引“under”是否为 (n > 0),以及索引“over”是否为 (n < array.Length)
Is your question whether the index or the array value with given index exists?
In case of array you can always be sure that index n "exists" if 0 < n < array.Length.
If you want to check for the array value, first check for (n > 0) for the index "under" and (n < array.Length) for the index "over"
我认为除了 Oded 所说的之外,正确的表达式可能是:
因为您正在检查
i-1
索引处的值。I think in addition to what Oded said, the correct expression might be:
because you are checking value at
i-1
index.从您的代码看来,“i”是从一开始的,而您的数组索引是从零开始的。所以你可以使用:
From your code, it appears that "i" is one-based and your array indexes are zero-based. So you could use: