有一数组
int c = 0;
int[] i = new int{1,8,9,11,12,19,33,100,101,200}
如果c等于1
结果:1和8
如果c等于33
结果:19和100
如果c等于200
结果:101和200
请问怎么取到它左右两边的值呢?谢谢!
------解决方案--------------------------------------------------------
- C# code
int num1, num2; //前后两个数num1 = num2 = 0;int c = 101;int[] i = { 1, 8, 9, 11, 12, 19, 33, 100, 101, 200 };for (int k = 0; k < i.Length; k++){ if (i[k] == c) { num1 = i[k - 1 < 0 ? k : k - 1]; num2 = i[k + 1 == i.Length ? k : k + 1]; break; }}
------解决方案--------------------------------------------------------
int num1=0;
int num2=0;
int c = 100;
int[] i = { 1, 8, 9, 11, 12, 19, 33, 100, 101, 200 };
int len=i.Length;//我都叫我手下这么定义一个值,不然循环里面如果数量大的情况会变慢
for (int k = 0; k < len; k++)
{
if (i[k] == c)
{
num1 = i[k - 1];
if((k + 1)>len)
{
num2 =0;
}else{
num2=i[k +1];
}
break;
}
}