c# 已知一个list包含一个最大和最小的两个数, 传递一个数与值比较 放回新的最大和最小值,排除0和异常数
时间: 2024-11-15 08:26:33 浏览: 0
在C#中,你可以创建一个名为`FindMinMaxExcludingZeroAndExceptionalNumbers`的方法来实现这个功能。首先,你需要遍历列表,找到当前的最大值和最小值,同时排除0和异常数。下面是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
public class MaxMinCalculator
{
public (int max, int min) FindMinMaxExcludingZeroAndExceptionalNumbers(List<int> numbers, int value)
{
if (numbers == null || numbers.Count == 0)
throw new ArgumentException("List is empty or null");
int? currentMax = null;
int? currentMin = null;
foreach (int number in numbers)
{
if (number == 0)
continue; // 排除0
try
{
if (currentMax == null || number > currentMax.Value)
currentMax = number;
else if (currentMin == null || number < currentMin.Value)
currentMin = number;
}
catch (Exception ex) when (ex is ArgumentException || ex is DivideByZeroException) // 排除异常数值
{
continue;
}
}
// 如果value不在范围内,则更新max和min
if (value != 0 && (currentMax == null || value > currentMax.Value))
currentMax = value;
if (value != 0 && (currentMin == null || value < currentMin.Value))
currentMin = value;
return (currentMax ?? default(int), currentMin ?? default(int));
}
}
```
然后,你可以这样使用这个类:
```csharp
List<int> numbers = new List<int> { 5, -3, 0, 7, 2, 9 };
int valueToCompare = 4;
MaxMinCalculator calculator = new MaxMinCalculator();
var result = calculator.FindMinMaxExcludingZeroAndExceptionalNumbers(numbers, valueToCompare);
Console.WriteLine($"Max: {result.max}, Min: {result.min}");
```
阅读全文