【问题标题】:Is there a way to make an Int variable equal (==) to all the numbers stored in an Array?有没有办法使 Int 变量等于(==)存储在数组中的所有数字?
【发布时间】:2020-09-26 10:38:30
【问题描述】:

好的,所以我是编码新手,我刚刚在这里开设了一个帐户以获得一些帮助。 我的任务是编写一个应用程序,该应用程序将在控制台中打印 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++;
            }

感谢您的建议!

【问题讨论】:

  • 除非明确指示您使用数组,否则我会使用 for 循环 并将循环变量显式与 32、44 和 47 进行比较。
  • 使用 System.Linq; => num.Contains(numZero);

标签: c# arrays .net console integer


【解决方案1】:

您可以使用从 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,请将 &lt;= 更改为 &lt;,或使用 Range(0, 100)

【讨论】:

  • 谢谢,这在过去帮助了我!现在回想起来,我会微笑着。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 2017-02-12
  • 2021-06-29
  • 1970-01-01
相关资源
最近更新 更多