有没有办法使 Int 变量等于 (==) 存储在数组中的所有数字?
Is there a way to make an Int variable equal (==) to all the numbers stored in an Array?
好的,我是编码新手,我刚刚在这里开设了一个帐户以获得一些帮助。
我的任务是编写一个应用程序,该应用程序将在控制台中打印 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++;
}
感谢指教!
您可以使用从 0 到 100 的 for 循环,并在循环中测试数组中的索引 Exists()
是否不打印 else 以打印。
您也可以使用 Linq 扩展方法 Contains()
而不是 Array.Exists()
。
这样做你将有 3 行代码:
- 为
- 如果 !contains
- 打印(如果包含则什么也不做)。
因此你可以试试这个:
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)
.
好的,我是编码新手,我刚刚在这里开设了一个帐户以获得一些帮助。 我的任务是编写一个应用程序,该应用程序将在控制台中打印 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++;
}
感谢指教!
您可以使用从 0 到 100 的 for 循环,并在循环中测试数组中的索引 Exists()
是否不打印 else 以打印。
您也可以使用 Linq 扩展方法 Contains()
而不是 Array.Exists()
。
这样做你将有 3 行代码:
- 为
- 如果 !contains
- 打印(如果包含则什么也不做)。
因此你可以试试这个:
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)
.