boolean用作搜索数组中的数字的标志

时间:2018-03-05 03:48:15

标签: c#

int[] numbers = { 1, 2, 3, 4, 5, 6 };
int search = 10;
bool found = false;
foreach(var eachNum in numbers)
{
    if (eachNum.Equals(search))
    {
        found = true;
        Console.WriteLine("found");
        Console.WriteLine(search);
        break;
    } 
}
if (!found) // !found == false
{ 
    Console.WriteLine("not found");
}
Console.ReadKey(); 

在上面的例子中,if(!found)表示if(found == false)found == false对我有意义,但!found没有。为什么这两个是相同的,因为if !found == false,而不是找到的值应该是真的。

3 个答案:

答案 0 :(得分:0)

似乎你需要有人澄清你所看到的。

以下是您在程序中可能会看到的一些案例:

//debug your program and watch the value of the variable named: found.
if (true)  //if "found" is true
{
    //enter
}
if (false)  //if "found" is false
{
    //don't enter
}
if (!true)  //if "found" is not true, which means it's false.
{
    //don't enter
}
if (!false)  //if "found" is not false, which means it's true
{
    //enter
}

正如您当前发布的那样,found的值永远不会是true,因为search = 10,并且您没有值10你的int[] numbers

答案 1 :(得分:0)

这只是使用不同的方法来编写相同的布尔值 表达

if语句评估它给出的表达式,如果表达式求值为true,则执行以下代码块。

if (!found)if (found == false)是等价的,因为两个表达式的真值表是相同的。下表显示了变量found的可能值,以及每个表达式的结果值:

found    !found    found == false
---------------------------------
false    true      true
true     false     false

作为进一步的解释:

!found评估变量值的逻辑否定,因此如果true中的值然后它评估为false,反之亦然。

found == falsefound中的值与值false进行比较,因此如果found的值当前为false,则比较结果为{ {1}}因为这两个值是相同的。

另一种思考方式true是写!found的另一种方式。

答案 2 :(得分:-2)

当发现是假的时,!发现是真的。当找到为true时,那么!found为false。 !发现并不代表发现== false。原谅我可怜的英语。国人的话,可以用中文交流一下。

相关问题