首页 > 解决方案 > 有没有办法使 Int 变量等于(==)存储在数组中的所有数字?

问题描述

好的,所以我是编码新手,我刚刚在这里开设了一个帐户以获得一些帮助。我的任务是编写一个应用程序,该应用程序将在控制台中打印 0-100 的数字。但不是“32、44 和 77”。我知道我可以做很多 If 语句,但我的问题是我是否可以将三个数字存储在一个数组中,然后说:

        int numZero = 0;
        int[] num = { 32, 44, 77 };
        
        while (numZero <= 100)
        {
            Console.WriteLine(numZero);
            numZero++;

         // I know the num needs to have a value assigned. But can I make the "numZero" go through the three numbers in num?
           
            if (numZero == num [])  
            {
                numZero++;
            }

感谢您的建议!

标签: c#arrays.netconsoleinteger

解决方案


您可以使用从 0 到 100 的 for 循环,并在循环中测试Exists()数组中的索引是否不打印,否则打印。

您还可以使用 Linq 扩展方法Contains()代替Array.Exists().

这样做你将有 3 行代码:

  • 为了
  • 如果!包含
  • 打印(如果包含,你什么也不做)。

因此你可以试试这个:

using System.Linq;

int[] num = { 32, 44, 77 };

for ( int index = 0; index <= 100; index++ )
  if ( !num.Contains(index) )
    Console.WriteLine(index);

你也可以写:

foreach ( int index in Enumerable.Range(0, 101) )
  if ( !num.Contains(index) )
    Console.WriteLine(index);

使用Enumerable.Range避免了操作索引和增量,因此代码更干净,更安全。

注意:如果 100 不包含更改<=<,或使用Range(0, 100)


推荐阅读