“,“总是返回false
本文关键字:总是返回 false 返回 | 更新日期: 2023-09-27 18:16:10
我想检查数组中的某个值是否小于10且大于1。问题是,当我运行代码时,它总是返回-1,如下面的示例所示。我做错了什么?
int[] note = new int[5] {2, 3, 4, 5};
foreach (int element in note)
{
if(element <= 10 & element >= 0)
suma = suma + element;
else
return -1;
}
您刚刚忘记了suma的返回。在此之前,离开函数的唯一方法是返回-1。
如果有一个元素不符合条件,它将返回-1
int[] note = new int[4] {2, 3, 4, 5};
int suma = 0;
foreach (int element in note)
{
if (element <= 10 & element >= 0)
suma = suma + element;
// You may want to remove the following part
else
return -1;
}
return suma; // This was missing
下面是没有-1的代码运行的情况https://dotnetfiddle.net/t3uL1G
您还可以使用Linq只对符合条件的所有元素求和,如下所示:
using System.Linq;
...
int suma = note.Where(e => e < 11 && e > 0).Sum(); // + 0 is redundant.