我一直在弄乱 C# 中的 Lambda 表达式,自学,并试图在这里测试自己。我的代码的问题不在于评估数组的这些设置条件,而是我很难捕获用户输入以构建数组。尝试了几种不同的方法,其中一些在这里提到,但似乎无法使它们适应我的代码。此外,任何关于简化我的表达式以检查它是否只有奇数或偶数的输入将不胜感激!我觉得他们有点臃肿。谢谢!
using System;
namespace BuildingArrays
{
class Program
{
static void Main(string[] args)
{
int[] numbers = {Int32.TryParse(string, Console.ReadLine())};
bool hasOddOnly = Array.Exists(numbers, (int num) =>
{
bool hasEven = num % 2 == 0;
return hasEven;
});
hasOddOnly = !hasOddOnly;
bool hasEvenOnly = Array.Exists(numbers, (int num) =>
{
bool hasOdd = num % 2 != 0;
return hasOdd;
});
hasEvenOnly = !hasEvenOnly;
bool hasOddAnd4 = Array.Exists(numbers, (int num) =>
{
bool hasOdd = num % 2 != 0;
bool is4 = num == 4;
return is4 && hasOdd;
});
bool multipleOf4 = Array.Exists(numbers, (int num)=>
{
bool multiple = num % 4 == 0;
bool multiple2 = num % 3 == 0;
return multiple || multiple2;
});
bool multipleOf4and3 = Array.Exists(numbers, (int num)=>
{
bool multipleBoth = num % 4 == 0 && num % 3 == 0;
return multipleBoth;
});
Console.WriteLine($"This array contains odd numbers and 4 is {hasOddAnd4}");
Console.WriteLine($"This array contains ONLY odd numbers is {hasOddOnly}.");
Console.WriteLine($"This array contains ONLY even numbers is {hasEvenOnly}.");
Console.WriteLine($"This array contains either a multiple of 4, or a multiple of 3 is {multipleOf4}.");
Console.WriteLine($"This array contains a number which is both a multiple of 4 and 3 is {multipleOf4and3}");
}
}
}
Array.Exists
将Predicate<T>
作为第二个参数。 它应该看起来像这样:
bool hasEven = Array.Exists(numbers, x => x % 2 == 0);
要填充数组,您将需要这样的东西:
for (int i=0; i< numbers.Length; i++)
numbers[i] = Int32.Parse(Console.ReadLine());
进一步阅读
Array.存在于 MSDN
上 如何在 C# 中从用户输入填充数组