C# 在ArrayList中查找负数的最长部分
我有这个:C# 在ArrayList中查找负数的最长部分,c#,C#,我有这个: struct Weather { public int day; public int temperature; public Weather(int x, int y) { day = x; temperature = y; } } 我有一个ArrayList,它收集通过结构创建的所有数据: ArrayList wthrList = new ArrayList(); 让我们在ArrayList中有30个元素。“d
struct Weather {
public int day;
public int temperature;
public Weather(int x, int y) {
day = x;
temperature = y;
}
}
我有一个ArrayList,它收集通过结构创建的所有数据:
ArrayList wthrList = new ArrayList();
让我们在ArrayList中有30个元素。“day”变量取值范围为1到30。“温度”变量取-30到30之间的值(由随机变量生成)。我需要找到负数的最长部分。这意味着如果你有一个数组{0,-1,-2,3,-3,-4,-5,3},那么你将得到答案3(从索引4到6(-3,-4和-5))。我已经有了这段代码,但现在我被卡住了
foreach (Weather w in wthrList) {
if (w.temperature < 0) {
}
}
foreach(天气列表中的天气){
如果(w.温度<0){
}
}
int negCount=0;
int maxNegCount=0;
foreach(天气列表中的天气)
{
负计数=(w.温度<0)?负计数+1:0;
maxNegCount=Math.max(negCount,maxNegCount);
}
int negCount=0;
int maxNegCount=0;
foreach(天气列表中的天气)
{
负计数=(w.温度<0)?负计数+1:0;
maxNegCount=Math.max(negCount,maxNegCount);
}
Ok,我得说:ArrayList
被它的泛型版本List
超越了很多……好吧,我得说:ArrayList
被它的泛型版本List
超越了很多……这个答案是错误的。交换else子句中的行,那么它将起作用。如果温度值为{1,1,1,-1},您将得到错误的答案。negCount将等于1,但maxNegCount将等于0。此答案是错误的。交换else子句中的行,那么它将起作用。如果温度值为{1,1,1,-1},您将得到错误的答案。negCount将等于1,但maxNegCount将等于0。
int negCount = 0;
int maxNegCount = 0;
foreach (Weather w in wthrList)
{
negCount = (w.temperature < 0) ? negCount + 1 : 0;
maxNegCount = Math.max(negCount, maxNegCount);
}